/*
NomeObjeto: SNK_OBJETO_EXISTE
TipoObjeto: FUNCTION
NomeTabela: SNK_OBJETO_EXISTE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_OBJETO_EXISTE( VALOR VARCHAR )
   RETURN VARCHAR2 IS
   V_INPUT   VARCHAR2( 1 ) := VALOR;
BEGIN
   RETURN NVL( V_INPUT, '' );
END;
/

/*
NomeObjeto: SNK_COLUNA_EXISTE
TipoObjeto: FUNCTION
NomeTabela: SNK_COLUNA_EXISTE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_COLUNA_EXISTE( P_TABELA VARCHAR, P_COLUNA VARCHAR )
RETURN INT AS 
 V_COUNT INT;
BEGIN
  
  SELECT COUNT(1)
  INTO V_COUNT
  FROM USER_TAB_COLUMNS
  WHERE TABLE_NAME = P_TABELA
  AND COLUMN_NAME = P_COLUNA;
  
  RETURN V_COUNT; 
END;
/

/*
NomeObjeto: AD_MOVIMENTOCX_MAX
TipoObjeto: TABLE
NomeTabela: AD_MOVIMENTOCX_MAX
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MOVIMENTOCX_MAX
(
   ID                   NUMBER NOT NULL 
 , ID_CAIXA_MAX         NUMBER NOT NULL 
 , ACAO                 NUMBER NOT NULL 
 , DHACAO               DATE
 , CODPRESTACAOCONTAC   VARCHAR2( 200 )
 , CODPRESTACAOCONTAI   VARCHAR2( 200 )
 , DATALANCAMENTO       DATE
 , NUMTRANSVENDA        NUMBER
 , TIPO                 NUMBER
 , VALOR                NUMBER
 , VLJUROS              NUMBER
 , VLDESCONTO           NUMBER
 , NUMPEDRCA            NUMBER
 , EXCLUIDO             CHAR( 1 )
 , ID_ERP               NUMBER
 , FORMAPAGAMENTO       NUMBER
 , NUFIN                NUMBER
 , NUBCO                NUMBER
 , DTNEG                DATE
 , DTVENC               DATE
 , DHMOV                DATE
 , DTALTER              DATE
 , RECDESP              NUMBER
 , CODCTABCOINT         NUMBER
 , CODTIPTIT            NUMBER
 , DESDOBRAMENTO        NUMBER
 , VLRDESDOB            NUMBER
 , VLRDESC              NUMBER
 , VLRJUROS             NUMBER
 , VLRLANCSNK           NUMBER
 , SALDOSNK             NUMBER
 , CODLANC              NUMBER
)
/

/*
NomeObjeto: AD_CAIXA_MAX
TipoObjeto: TABLE
NomeTabela: AD_CAIXA_MAX
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_CAIXA_MAX
(
   ID                   NUMBER NOT NULL ENABLE
 , ACAO                 NUMBER NOT NULL ENABLE
 , DHACAO               DATE
 , CODPRESTACAOCONTAC   VARCHAR2( 200 )
 , DATAABERTURA         DATE
 , DATAFECHAMENTO       DATE
 , CODUSUR              NUMBER
 , NUMCARMANIF          VARCHAR2( 100 )
 , NUMLACRE             NUMBER
 , TOTALDESPESAS        NUMBER
 , TOTALRECEBIMENTOS    NUMBER
 , TOTALDEPOSITOS       NUMBER
 , NUCAIXA              NUMBER
 , DTFECHAMENTO         DATE
 , DTABERTURA           DATE
 , PRIMARY KEY( ID )
)
/

/*
NomeObjeto: TEIPCV_MAXIMA
TipoObjeto: TABLE
NomeTabela: TEIPCV_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE TEIPCV_MAXIMA
(
   ID            NUMBER( 10 ) PRIMARY KEY
 , NUFIN         NUMBER( 10 )
 , CODVEND       NUMBER( 10 )
 , TIPO          CHAR( 1 )
 , CAIXAMX       VARCHAR2( 40 )
 , MOVIMENTOMX   VARCHAR2( 40 )
 , MENSAGEM      VARCHAR2( 1000 )
 , CODERRO       NUMBER( 10 )
 , JSONREQUEST   VARCHAR2( 4000 )
)
/

/*
NomeObjeto: AD_PEDIDO_MAXIMA
TipoObjeto: TABLE
NomeTabela: AD_PEDIDO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_PEDIDO_MAXIMA
(
   NUNOTA               NUMBER PRIMARY KEY
 , AD_MAXIMA_NUMCAR     VARCHAR( 50 )
 , AD_MAXIMA_IDPEDIDO   VARCHAR( 20 )
 , AD_MAXIMA_PEDIDO     VARCHAR( 50 )
 , PESOBRUTO            FLOAT
)
/

/*
NomeObjeto: AD_MAXIMA_MENSAGENS
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_MENSAGENS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_MENSAGENS
(
   CODMENSAGEM      NUMBER( 5 ) NOT NULL
 , CODVEND          NUMBER( 10 ) NOT NULL
 , DTMENSAGEM       DATE
 , MENSAGEM         CLOB
 , STATUSMENSAGEM   CHAR( 1 )
 , CODUSU           NUMBER( 10 )
)
/

/*
NomeObjeto: AD_MAXIMA_PROCESSOS
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_PROCESSOS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_PROCESSOS
(
   ID          NUMBER( 5 )
 , DESCRICAO   VARCHAR2( 100 )
 , ID_ACAO     NUMBER( 5 )
)
/

/*
NomeObjeto: AD_INSTANCIAS_MAXIMA
TipoObjeto: TABLE
NomeTabela: AD_INSTANCIAS_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_INSTANCIAS_MAXIMA
(
   ID          INT NOT NULL
 , DESCRICAO   VARCHAR( 200 ) NOT NULL
)
/

/*
NomeObjeto: AD_INSTANCIA_ACAO_MAXIMA
TipoObjeto: TABLE
NomeTabela: AD_INSTANCIA_ACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_INSTANCIA_ACAO_MAXIMA
(
   ID_LIGACAO     INT NOT NULL
 , ID_INSTANCIA   INT NOT NULL
 , NUAAG          INT NOT NULL
)
/

/*
NomeObjeto: POPULAR_TABELA_INSTANCIA_MAXIMA
TipoObjeto: PROCEDURE
NomeTabela: AD_INSTANCIAS_MAXIMA
Executar  : SEMPRE
*/ 

DECLARE
BEGIN
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 1 AS ID ,''Cidades'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 1)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 2 AS ID ,''Regiões'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 2)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 3 AS ID ,''Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 3)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 4 AS ID ,''Produtos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 4)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 5 AS ID ,''Departamentos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 5)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 6 AS ID ,''Estoques'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 6)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 7 AS ID ,''Vendedores'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 7)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 8 AS ID ,''Supervisores'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 8)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 9 AS ID ,''Cobranças'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 9)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 10 AS ID ,''Empresas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 10)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 11 AS ID ,''Produtos x Empresa'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 11)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 12 AS ID ,''Praças'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 12)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 13 AS ID ,''Mix Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 13)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 14 AS ID ,''Endereços Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 14)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 15 AS ID ,''Saldo Flex'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 15)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 16 AS ID ,''Tabelas de Preço'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 16)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 17 AS ID ,''Crédito Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 17)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 18 AS ID ,''Fornecedores'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 18)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 19 AS ID ,''Titulos em Aberto'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 19)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 20 AS ID ,''Hist. Pedidos Cabeçalho'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 20)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 21 AS ID ,''Hist. Pedidos Itens'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 21)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 22 AS ID ,''Veículos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 22)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 23 AS ID ,''Marcas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 23)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 24 AS ID ,''Planos Pagamentos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 24)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 25 AS ID ,''Tributos (Mestre)'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 25)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 26 AS ID ,''Funcionários'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 26)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 27 AS ID ,''Pedidos Pré-Venda'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 27)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 28 AS ID ,''Atividades'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 28)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 29 AS ID ,''Planos Pgto x Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 29)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 31 AS ID ,''Roteirização'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 31)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 32 AS ID ,''Pedidos Pronta Entrega'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 32)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 33 AS ID ,''Embalagens'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 33)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 34 AS ID ,''Clientes x Vendedores'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 34)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 35 AS ID ,''Cobranças x Planos de Pagamento'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 35)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 36 AS ID ,''Remessa Simbólica Veículo'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 36)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 37 AS ID ,''Naturezas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 37)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 38 AS ID ,''Carregamentos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 38)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 39 AS ID ,''Contas Bancárias'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 39)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 40 AS ID ,''Doc. Eletrónico'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 40)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 42 AS ID ,''Última Compra'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 42)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 43 AS ID ,''Notas Saída'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 43)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 44 AS ID ,''Remessa Estoque Veículo'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 44)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 46 AS ID ,''Motoristas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 46)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 47 AS ID ,''Rotas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 47)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 49 AS ID ,''Promoções'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 49)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 50 AS ID ,''Tabelas Flex'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 50)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 51 AS ID ,''Visitas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 51)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 53 AS ID ,''Bancos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 53)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 54 AS ID ,''Prestação Contas Vendedor'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 54)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 55 AS ID ,''Código Fiscal'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 55)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 56 AS ID ,''Series'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 56)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 57 AS ID ,''Categorias'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 57)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 58 AS ID ,''Subcategorias'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 58)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 59 AS ID ,''Tributos (Detalhe)'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 59)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 60 AS ID ,''Notas Saída Itens'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 60)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 61 AS ID ,''Registro Ponto Funcionários'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 61)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 62 AS ID ,''Retorno Roteirização'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 62)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 63 AS ID ,''Obter Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 63)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 64 AS ID ,''Obter Geolocalização Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 64)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 65 AS ID ,''Compras/Devoluções de Vendas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 65)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 66 AS ID ,''Compras/Devoluções de Vendas - Itens'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 66)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 67 AS ID ,''Devoluções x Vendas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 67)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 68 AS ID ,''Compras Pendentes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 68)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 69 AS ID ,''Metas de Vendas'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 69)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 70 AS ID ,''Contatos de Clientes'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 70)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 71 AS ID ,''Transportadoras'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 71)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 72 AS ID ,''Lotes de Estoque'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 72)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 73 AS ID ,''Mensagens Vendedores'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 73)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 74 AS ID ,''Retorno Crítica Pedidos'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 74)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 75 AS ID ,''Código de Barras'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 75)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 76 AS ID ,''Promoções Valor'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 76)';
   EXECUTE IMMEDIATE
      'INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 77 AS ID ,''Ordem de Carga'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 77)';
END;
/

/*
NomeObjeto: AD_MAXIMA_CARREGAMENTOS
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_CARREGAMENTOS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_CARREGAMENTOS
(
   NUMCAR         NUMBER( 10 ) NOT NULL
 , CODVEND        NUMBER( 5 ) NOT NULL
 , DTFECHAMENTO   DATE
 , DTABERTURA     DATE DEFAULT SYSDATE
)
/

/*
NomeObjeto: AD_MAXIMA_PRODFILIAL
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_PRODFILIAL
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_PRODFILIAL
(
   CODPROD   NUMBER( 10 ) NOT NULL
 , CODEMP    NUMBER( 5 ) NOT NULL
)
/

/*
NomeObjeto: AD_MAXIMA_PERSONALIZADOS
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_PERSONALIZADOS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_PERSONALIZADOS (
    ID_PERSONALIZACAO INTEGER CONSTRAINT PK_AD_MAXIMA_PERSONALIZADOS PRIMARY KEY
  , DESCRICAO VARCHAR2(200)
  , CODTAREFA INTEGER
  , NOME_VIEW VARCHAR2(200)
  , ENDPOINT VARCHAR2(200)
  , DELETAR CHAR(1) DEFAULT 'N' 
)
/

/*
NomeObjeto: AD_MAXIMA_INTEGRA
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMA_INTEGRA
(
   ID        INTEGER NOT NULL
 , TIPO      INTEGER NOT NULL
 , CHAVE     VARCHAR2( 400 ) NOT NULL
 , MD5       CHAR( 32 )
 , DHALTER   DATE
)
/

/*
NomeObjeto: AD_MAXCONF
TipoObjeto: TABLE
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXCONF
(
   ID                          NUMBER( 5 )
 , MAXGRAVALOG                 CHAR( 1 ) DEFAULT 'N' NOT NULL
 , MAXFINMODELO                NUMBER( 10 )
 , QTD_DIAS_HIST_VENDAS        NUMBER( 5 ) DEFAULT 30 NOT NULL
 , MAXTOPBAIXA                 NUMBER( 5 )
 , MAXTOPTRANSFBANCARIA        NUMBER( 5 )
 , MODELOREMESSA               NUMBER( 10 )
 , MODELORETORNO               NUMBER( 10 )
 , MODELOPRONTAENTREGA         NUMBER( 10 )
 , MODELOPRONTAENTREGA_NOTA    NUMBER( 10 )
 , LOCAL_TRANSITO              NUMBER( 10 )
 , LOCAL_EMPRESA               NUMBER( 10 )
 , QTD_DIAS_NOTAS              NUMBER( 5 ) DEFAULT 7 NOT NULL
 , QTD_DIAS_CARREGAMENTO       NUMBER( 5 ) DEFAULT 7 NOT NULL
 , QTD_DIAS_CAIXAS             NUMBER( 5 ) DEFAULT 2 NOT NULL
 , QTD_DIAS_COMPRAS_PENDENTE   NUMBER( 5 ) DEFAULT 30 NOT NULL
 , QTD_DIAS_PONTO              NUMBER( 5 ) DEFAULT 1
 , ENVIA_PD_PENDENTE           CHAR( 1 ) DEFAULT 'N' NOT NULL
 , QTD_DIAS_ROTEIRIZAR         NUMBER( 5 ) DEFAULT 1 NOT NULL
 , TOP_ENTREGA_BALCAO          NUMBER( 5 )
 , TOP_ORCAMENTO               NUMBER( 5 )
 , AD_CODLOCALORIG             NUMBER( 10 )
 , AD_URLAPI                   VARCHAR2( 400 )
 , AD_USUARIO                  VARCHAR2( 400 )
 , AD_SENHA                    VARCHAR2( 400 )
 , AD_URLAPIPDV                VARCHAR2( 400 )
 , TIT_CARTORIO                NUMBER( 10 )
 , TIT_PROTESTO                NUMBER( 10 )
 , NOTMODPREVENDA              NUMBER( 10 )
 , ENVIA_GERENTE               CHAR( 1 ) DEFAULT 'N' NOT NULL
 , TOP_RETORNO_DESCARGA        DECIMAL( 10, 0 )
 , TOP_NF_RETORNO              NUMBER( 5 )
 , ESTVEITRANSF                CHAR( 1 ) DEFAULT 'N' NOT NULL
 , CODEMPBASE                  NUMBER( 10 )
)
/

/*
NomeObjeto: AD_MAXIMALOG
TipoObjeto: TABLE
NomeTabela: AD_MAXIMALOG
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE AD_MAXIMALOG
(
   ID              NUMBER( 10 ) NOT NULL
 , TIPO_REGISTRO   NUMBER( 2 )
 , OPERACAO        CHAR( 1 )
 , SENTIDO         CHAR( 1 )
 , TIPO_RETORNO    CHAR( 1 )
 , MENSAGEM        CLOB
 , STACKTRACE      CLOB
 , CHAVE           VARCHAR2( 400 )
 , DH_LOG          DATE
 , REQUEST         VARCHAR2( 400 )
 , RESPONSE        CLOB
 , BODY            CLOB
 , TIPO_LOG        INTEGER
)
/

/*
NomeObjeto: TRIBUTACAO_MAXIMA
TipoObjeto: TABLE
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE TABLE TRIBUTACAO_MAXIMA
(
   IDLINHA                        NUMBER
 , CODEMP                         NUMBER
 , CODPROD                        NUMBER
 , CODFILIALNF                    NUMBER
 , UFDESTINO                      VARCHAR2( 2 BYTE )
 , CODOPER                        NUMBER
 , CODCLI                         NUMBER
 , AGREGARIPICALCULOST            VARCHAR2( 1 BYTE )
 , ALIQICMS1                      NUMBER
 , ALIQICMS1FONTE                 NUMBER
 , ALIQICMS2                      NUMBER
 , ALIQICMS2FONTE                 NUMBER
 , CODICM                         NUMBER
 , CODICMPF                       NUMBER
 , CODICMPRODRURAL                NUMBER
 , CODICMTAB                      NUMBER
 , CODICMTABPF                    NUMBER
 , IVA                            NUMBER
 , IVAFONTE                       NUMBER
 , MOSTRARPVENDASEMIPI            VARCHAR2( 1 BYTE )
 , MOSTRARPVENDASEMST             VARCHAR2( 1 BYTE )
 , OBS                            VARCHAR2( 1 BYTE )
 , PAUTA                          NUMBER
 , PERACRESCIMOFUNCEP             NUMBER
 , PERACRESCIMOPF                 NUMBER
 , PERBASEREDNRPA                 NUMBER
 , PERCACRESICMSPF_PI             NUMBER
 , PERCBASERED                    NUMBER
 , CONSUMIDOR                     VARCHAR2( 1 BYTE )
 , TIPOSN                         NUMBER
 , PERCBASEREDST                  NUMBER
 , PERCBASEREDSTFONTE             NUMBER
 , PERCBASESTRJ                   NUMBER
 , PERCDESCCOFINS                 NUMBER
 , PERCDESCPIS                    NUMBER
 , PERDESCICMISENCAO              NUMBER
 , PERDESCPISSUFRAMA              NUMBER
 , PERDESCREPASSE                 NUMBER
 , PERDESCSUFRAMA                 NUMBER
 , RIOLOGISENTOST                 NUMBER
 , SITTRIBUT                      NUMBER
 , TIPOCALCULOGNRE                VARCHAR2( 1 BYTE )
 , TV9ISENTOST                    NUMBER
 , USAVALORULTENTBASEST           VARCHAR2( 1 BYTE )
 , USAVALORULTENTBASEST2          VARCHAR2( 1 BYTE )
 , USAVLULTENTMEDIOBASEST         VARCHAR2( 1 BYTE )
 , UTILIZAPERCBASEREDPF           VARCHAR2( 1 BYTE )
 , CODFISCALVENDAPRONTAENT        NUMBER
 , CODFISCALVENDAPRONTAENTINTER   NUMBER
 , CODFISCALBONIFIC               NUMBER
 , CODFISCALBONIFICINTER          NUMBER
 , PRIORIDADE                     NUMBER
 , PERCBASEREDCONSUMIDOR          NUMBER
 , PERCREDPVENDASIMPLESNAC        NUMBER
)
/

/*
NomeObjeto: PERACRESCIMOFUNCEP
TipoObjeto: COLUMN
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TRIBUTACAO_MAXIMA ADD PERACRESCIMOFUNCEP FLOAT
/

/*
NomeObjeto: ALIQICMSFECP
TipoObjeto: COLUMN
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TRIBUTACAO_MAXIMA ADD ALIQICMSFECP FLOAT
/

/*
NomeObjeto: TIPO_REGISTRO
TipoObjeto: COLUMN
NomeTabela: AD_MAXIMALOG
Executar  : SE_EXISTIR
*/ 

ALTER TABLE AD_MAXIMALOG MODIFY TIPO_REGISTRO NUMBER(5)
/

/*
NomeObjeto: AD_BROKER
TipoObjeto: COLUMN
NomeTabela: TSIEMP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIEMP ADD AD_BROKER VARCHAR(1)
/

/*
NomeObjeto: AD_NUMTABELA
TipoObjeto: COLUMN
NomeTabela: TGFTAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTAB ADD AD_NUMTABELA NUMBER(10)
/

/*
NomeObjeto: AD_CODREPRESENTANTE
TipoObjeto: COLUMN
NomeTabela: TGFTAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTAB ADD AD_CODREPRESENTANTE NUMBER(10)
/

/*
NomeObjeto: AD_CODESTABELECIMENTO
TipoObjeto: COLUMN
NomeTabela: TGFTAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTAB ADD AD_CODESTABELECIMENTO NUMBER(10)
/

/*
NomeObjeto: AD_COBRANCABROKER
TipoObjeto: COLUMN
NomeTabela: TGFTIT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTIT ADD AD_COBRANCABROKER VARCHAR(1)
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFVOA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFVOA ADD AD_MAXIMA CHAR(1) DEFAULT 'S' NOT NULL
/

/*
NomeObjeto: AD_NUMEROTABELA
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_NUMEROTABELA VARCHAR2(20)
/

/*
NomeObjeto: AD_CODIGOESTABELECIMENTO
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_CODIGOESTABELECIMENTO VARCHAR2(20)
/

/*
NomeObjeto: AD_MAXIMA_TELENTREGA
TipoObjeto: COLUMN
NomeTabela: TGFCPL
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCPL ADD AD_MAXIMA_TELENTREGA VARCHAR(15)
/

/*
NomeObjeto: MAXRETORNOPARCIAL
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD (MAXRETORNOPARCIAL NUMBER (10))
/

/*
NomeObjeto: LOC_RETORNO_PARCIAL
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD (LOC_RETORNO_PARCIAL NUMBER (10))
/

/*
NomeObjeto: AD_MAXIMA_PED_ORIGEM
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_MAXIMA_PED_ORIGEM NUMBER(10)
/

/*
NomeObjeto: CODEMPBASE
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD CODEMPBASE NUMBER(10)
/

/*
NomeObjeto: PK_AD_MAXIMA_PRODFILIAL
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_PRODFILIAL
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_PRODFILIAL
ADD CONSTRAINT PK_AD_MAXIMA_PRODFILIAL PRIMARY KEY (CODPROD, CODEMP)
/

/*
NomeObjeto: AD_MAXIMA_IDFIN_CAIXA
TipoObjeto: COLUMN
NomeTabela: TGFFIN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFFIN ADD AD_MAXIMA_IDFIN_CAIXA VARCHAR2(100)
/

/*
NomeObjeto: AD_CODTIPOPER
TipoObjeto: COLUMN
NomeTabela: TGFPAR
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPAR ADD AD_CODTIPOPER NUMBER(10)
/

/*
NomeObjeto: AD_SERIENOTA
TipoObjeto: COLUMN
NomeTabela: TGFPAR
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPAR ADD AD_SERIENOTA CHAR(3)
/

/*
NomeObjeto: AD_MAXIMA_IDPEDIDO
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_MAXIMA_IDPEDIDO VARCHAR2(100)
/

/*
NomeObjeto: AD_MAXIMA_CODCOMBO
TipoObjeto: COLUMN
NomeTabela: TGFITE
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFITE ADD AD_MAXIMA_CODCOMBO NUMBER(10)
/

/*
NomeObjeto: AD_MAXIMA_IDMOVBCO
TipoObjeto: COLUMN
NomeTabela: TGFMBC
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFMBC ADD AD_MAXIMA_IDMOVBCO VARCHAR(100)
/

/*
NomeObjeto: AD_MAXIMA_IDCX
TipoObjeto: COLUMN
NomeTabela: TGFCAI
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAI ADD AD_MAXIMA_IDCX VARCHAR(100)
/

/*
NomeObjeto: AD_MAXIMA_IDFIN
TipoObjeto: COLUMN
NomeTabela: TGFFIN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFFIN ADD AD_MAXIMA_IDFIN VARCHAR(100)
/

/*
NomeObjeto: AD_MAXIMA_TIPO
TipoObjeto: COLUMN
NomeTabela: TGFPRO
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPRO ADD AD_MAXIMA_TIPO CHAR(1) --S eh Inflamaveis, N eh Normal, R - Refrigerado
/

/*
NomeObjeto: AD_CODCTABCOINT
TipoObjeto: COLUMN
NomeTabela: TGFVEN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFVEN ADD AD_CODCTABCOINT NUMBER(5)
/

/*
NomeObjeto: AD_MAXIMA_NUMCAR
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_MAXIMA_NUMCAR VARCHAR2(50)
/

/*
NomeObjeto: AD_MAXIMA_NUMCAR
TipoObjeto: COLUMN
NomeTabela: TGFORD
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFORD ADD AD_MAXIMA_NUMCAR VARCHAR2(50)
/

/*
NomeObjeto: AD_MAXIMA_VENDA_EMB
TipoObjeto: COLUMN
NomeTabela: TSIEMP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIEMP ADD AD_MAXIMA_VENDA_EMB CHAR(1) DEFAULT 'S' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA_RECEBE
TipoObjeto: COLUMN
NomeTabela: TGFTIT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTIT ADD AD_MAXIMA_RECEBE CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA_RECEBE
TipoObjeto: COLUMN
NomeTabela: TGFFIN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFFIN ADD AD_MAXIMA_RECEBE CHAR(1)
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFTIT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTIT ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA_LOCAL
TipoObjeto: COLUMN
NomeTabela: TGFVEN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFVEN ADD AD_MAXIMA_LOCAL NUMBER(10) DEFAULT 0 NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFTOP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTOP ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFMAR
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFMAR ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSIREG
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIREG ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFLOC
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFLOC ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFPRO
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPRO ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFTPV
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTPV ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFNTA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFNTA ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFPAR
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPAR ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSICID
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSICID ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSIEMP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIEMP ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFVEN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFVEN ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFNAT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFNAT ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFGRU
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFGRU ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSIBCO
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIBCO ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TGFVEI
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFVEI ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSIUSU
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSIUSU ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: COLUMN
NomeTabela: TSICTA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TSICTA ADD AD_MAXIMA CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMA_PEDIDO
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_MAXIMA_PEDIDO VARCHAR(50)
/

/*
NomeObjeto: DHLOG
TipoObjeto: COLUMN
NomeTabela: TEIPCV_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TEIPCV_MAXIMA ADD DHLOG DATE
/

/*
NomeObjeto: AD_TROCABONIFICADA
TipoObjeto: COLUMN
NomeTabela: TGFPAR
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFPAR ADD AD_TROCABONIFICADA CHAR(1) DEFAULT 'N'
/

/*
NomeObjeto: CKC_TIPREGISTRO_TFPAFDT
TipoObjeto: CONSTRAINT
NomeTabela: TFPAFDT
Executar  : SE_EXISTIR
*/ 

ALTER TABLE TFPAFDT DROP CONSTRAINT CKC_TIPREGISTRO_TFPAFDT
/

/*
NomeObjeto: CKC_TIPREGISTRO_TFPAFDT
TipoObjeto: CONSTRAINT
NomeTabela: TFPAFDT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TFPAFDT ADD
  CONSTRAINT CKC_TIPREGISTRO_TFPAFDT CHECK (TIPREGISTRO IN ('O','I','P','H'))
/

/*
NomeObjeto: GEOLOC
TipoObjeto: COLUMN
NomeTabela: TFPAFDT
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TFPAFDT ADD GEOLOC VARCHAR2(100)
/

/*
NomeObjeto: PK_MXM_CODMENSAGEM
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_MENSAGENS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_MENSAGENS 
ADD CONSTRAINT PK_MXM_CODMENSAGEM PRIMARY KEY (CODMENSAGEM)
/

/*
NomeObjeto: FK_TSIUSU_MXM_MSG
TipoObjeto: FOREIGN KEY
NomeTabela: AD_MAXIMA_MENSAGENS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_MENSAGENS
ADD CONSTRAINT FK_TSIUSU_MXM_MSG FOREIGN KEY(CODUSU) REFERENCES TSIUSU(CODUSU)
/

/*
NomeObjeto: FK_TGFVEN_MXM_MSG
TipoObjeto: FOREIGN KEY
NomeTabela: AD_MAXIMA_MENSAGENS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_MENSAGENS
ADD CONSTRAINT FK_TGFVEN_MXM_MSG FOREIGN KEY(CODVEND) REFERENCES TGFVEN(CODVEND)
/

/*
NomeObjeto: PK_AD_MAXIMA_PROCESSOS
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_PROCESSOS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_PROCESSOS
ADD CONSTRAINT PK_AD_MAXIMA_PROCESSOS PRIMARY KEY (ID)
/

/*
NomeObjeto: PK_AD_INSTANCIAS_MAXIMA
TipoObjeto: PRIMARY KEY
NomeTabela: AD_INSTANCIAS_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_INSTANCIAS_MAXIMA
ADD CONSTRAINT PK_AD_INSTANCIAS_MAXIMA PRIMARY KEY (ID)
/

/*
NomeObjeto: PK_AD_INSTANCIA_ACAO_MAXIMA
TipoObjeto: PRIMARY KEY
NomeTabela: AD_INSTANCIA_ACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_INSTANCIA_ACAO_MAXIMA
ADD CONSTRAINT PK_AD_INSTANCIA_ACAO_MAXIMA PRIMARY KEY(ID_LIGACAO)
/

/*
NomeObjeto: FK_INST_ACAO_INST_MAXIMA
TipoObjeto: FOREIGN KEY
NomeTabela: AD_INSTANCIA_ACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_INSTANCIA_ACAO_MAXIMA
ADD CONSTRAINT FK_INST_ACAO_INST_MAXIMA FOREIGN KEY(ID_INSTANCIA) REFERENCES AD_INSTANCIAS_MAXIMA(ID)
/

/*
NomeObjeto: FK_INSTANCIA_ACAO_TSIAAG
TipoObjeto: FOREIGN KEY
NomeTabela: AD_INSTANCIA_ACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_INSTANCIA_ACAO_MAXIMA
ADD CONSTRAINT FK_INSTANCIA_ACAO_TSIAAG FOREIGN KEY(NUAAG) REFERENCES TSIAAG(NUAAG)
/

/*
NomeObjeto: PK_AD_MAXIMA_CARREGAMENTOS
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_CARREGAMENTOS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_CARREGAMENTOS
ADD CONSTRAINT PK_AD_MAXIMA_CARREGAMENTOS PRIMARY KEY(NUMCAR)
/

/*
NomeObjeto: PD_AD_MAXIMA_PRODFILIAL
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_PRODFILIAL
Executar  : SE_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_PRODFILIAL DROP CONSTRAINT PD_AD_MAXIMA_PRODFILIAL
/

/*
NomeObjeto: PK_AD_MAXIMA_INTEGRA
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_INTEGRA
ADD CONSTRAINT PK_AD_MAXIMA_INTEGRA PRIMARY KEY ( ID )
/

/*
NomeObjeto: PK_AD_MAXIMALOG
TipoObjeto: PRIMARY KEY
NomeTabela: AD_MAXIMALOG
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMALOG
ADD CONSTRAINT PK_AD_MAXIMALOG PRIMARY KEY (ID)
/

/*
NomeObjeto: DTABERTURA
TipoObjeto: COLUMN
NomeTabela: AD_MAXIMA_CARREGAMENTOS
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXIMA_CARREGAMENTOS ADD DTABERTURA DATE DEFAULT SYSDATE
/

/*
NomeObjeto: TOP_RETORNO_DESCARGA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TOP_RETORNO_DESCARGA DECIMAL(10,0)
/

/*
NomeObjeto: LOCAL_EMPRESA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD LOCAL_EMPRESA NUMBER(10)
/

/*
NomeObjeto: ESTVEITRANSF
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD ESTVEITRANSF  CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: TOP_NF_RETORNO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TOP_NF_RETORNO  NUMBER(5)
/

/*
NomeObjeto: TOP_ORCAMENTO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TOP_ORCAMENTO   NUMBER(5)
/

/*
NomeObjeto: TOP_ENTREGA_BALCAO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TOP_ENTREGA_BALCAO   NUMBER(5)
/

/*
NomeObjeto: QTD_DIAS_NOTAS
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_NOTAS   NUMBER(5) DEFAULT 1 NOT NULL
/

/*
NomeObjeto: QTD_DIAS_COMPRAS_PENDENTE
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_COMPRAS_PENDENTE   NUMBER(5) DEFAULT 30 NOT NULL
/

/*
NomeObjeto: QTD_DIAS_PONTO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_PONTO NUMBER(5) DEFAULT 1
/

/*
NomeObjeto: MAXTOPTRANSFBANCARIA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD MAXTOPTRANSFBANCARIA NUMBER(5)
/

/*
NomeObjeto: QTD_DIAS_CAIXAS
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_CAIXAS NUMBER(5) DEFAULT 2 NOT NULL
/

/*
NomeObjeto: MODELOPRONTAENTREGA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD MODELOPRONTAENTREGA NUMBER(10)
/

/*
NomeObjeto: MODELOPRONTAENTREGA_NOTA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD MODELOPRONTAENTREGA_NOTA NUMBER(10)
/

/*
NomeObjeto: QTD_DIAS_HIST_VENDAS
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_HIST_VENDAS  NUMBER(5) DEFAULT 30 NOT NULL
/

/*
NomeObjeto: ENVIA_PD_PENDENTE
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD ENVIA_PD_PENDENTE CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: QTD_DIAS_ROTEIRIZAR
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_ROTEIRIZAR NUMBER(5) DEFAULT 1 NOT NULL
/

/*
NomeObjeto: LOCAL_TRANSITO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD LOCAL_TRANSITO NUMBER(10)
/

/*
NomeObjeto: MODELOREMESSA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD MODELOREMESSA NUMBER(10)
/

/*
NomeObjeto: MODELORETORNO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD MODELORETORNO NUMBER(10)
/

/*
NomeObjeto: QTD_DIAS_CARREGAMENTO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_CARREGAMENTO NUMBER(5) DEFAULT 7 NOT NULL
/

/*
NomeObjeto: TIT_CARTORIO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TIT_CARTORIO NUMBER(10)
/

/*
NomeObjeto: TIT_PROTESTO
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD TIT_PROTESTO NUMBER(10)
/

/*
NomeObjeto: NOTMODPREVENDA
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD NOTMODPREVENDA NUMBER(10)
/

/*
NomeObjeto: USALIMITEFLEX
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD USALIMITEFLEX CHAR(1) 
/

/*
NomeObjeto: ENVIA_GERENTE
TipoObjeto: COLUMN
NomeTabela: AD_MAXCONF
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE AD_MAXCONF ADD ENVIA_GERENTE CHAR(1) DEFAULT 'N' NOT NULL
/

/*
NomeObjeto: AD_MAXIMAORIGEMPD
TipoObjeto: COLUMN
NomeTabela: TGFTOP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTOP ADD AD_MAXIMAORIGEMPD VARCHAR(1)
/

/*
NomeObjeto: Alterar AD_MAXIMA Parceiro
TipoObjeto: PROCEDURE
NomeTabela: TGFPAR
Executar  : SEMPRE
*/ 

DECLARE
   P_COUNT   INT;
BEGIN
   SELECT COUNT( 1 )
     INTO P_COUNT
     FROM ALL_TAB_COLUMNS
    WHERE TABLE_NAME = 'TGFPAR'
      AND COLUMN_NAME = 'AD_MAXIMA_CLIENTE'
      AND OWNER = USER;

   IF P_COUNT = 0 THEN
      EXECUTE IMMEDIATE 'ALTER TABLE TGFPAR ADD AD_MAXIMA_CLIENTE CHAR(1)';

      EXECUTE IMMEDIATE 'ALTER TABLE TGFPAR ADD AD_MAXIMA_FORNECEDOR CHAR(1)';

      EXECUTE IMMEDIATE
         'ALTER TABLE TGFPAR ADD AD_MAXIMA_TRANSPORTADORA CHAR(1)';

      EXECUTE IMMEDIATE 'ALTER TABLE TGFPAR ADD AD_MAXIMA_MOTORISTA CHAR(1)';

      EXECUTE IMMEDIATE
         'UPDATE TGFPAR SET AD_MAXIMA_CLIENTE = ''S'' WHERE AD_MAXIMA = ''S'' AND CLIENTE = ''S''';

      EXECUTE IMMEDIATE
         'UPDATE TGFPAR SET AD_MAXIMA_FORNECEDOR = ''S'' WHERE AD_MAXIMA = ''S'' AND FORNECEDOR = ''S''';

      EXECUTE IMMEDIATE
         'UPDATE TGFPAR SET AD_MAXIMA_TRANSPORTADORA = ''S'' WHERE AD_MAXIMA = ''S'' AND TRANSPORTADORA = ''S''';

      EXECUTE IMMEDIATE
         'UPDATE TGFPAR SET AD_MAXIMA_MOTORISTA  = ''S'' WHERE AD_MAXIMA = ''S'' AND MOTORISTA = ''S''';

      EXECUTE IMMEDIATE 'ALTER TABLE TGFPAR DROP COLUMN AD_MAXIMA';
   END IF;
END;
/

/*
NomeObjeto: SQ_MAXIMA_INTEGRA
TipoObjeto: PROCEDURE
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SEMPRE
*/ 

DECLARE
   P_COUNT   NUMBER( 5 );
BEGIN
   P_COUNT := 0;
   --Criando sequence
   SELECT COUNT( 1 )
     INTO P_COUNT
     FROM USER_OBJECTS
    WHERE OBJECT_TYPE = 'SEQUENCE'
      AND OBJECT_NAME = 'SQ_MAXIMA_INTEGRA';

   IF P_COUNT = 0 THEN
      EXECUTE IMMEDIATE
         'CREATE SEQUENCE SQ_MAXIMA_INTEGRA START WITH 1  MAXVALUE 9999999999999999999999999999  MINVALUE 1 NOCYCLE CACHE 20  NOORDER';
   END IF;
END;
/

/*
NomeObjeto: AD_MAXIMA_STATUS
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD AD_MAXIMA_STATUS SMALLINT
/

/*
NomeObjeto: AD_MAXIMA_STATUS
TipoObjeto: COLUMN
NomeTabela: TGFCAN
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAN ADD AD_MAXIMA_STATUS SMALLINT
/

/*
NomeObjeto: AD_MAXIMA
TipoObjeto: PROCEDURE
NomeTabela: TGFGRU
Executar  : SEMPRE
*/ 

DECLARE
   V_COUNT   INT;
BEGIN
   SELECT COUNT( 1 )
     INTO V_COUNT
     FROM TDDCAM
    WHERE NOMETAB = 'TGFGRU'
      AND NOMECAMPO = 'AD_MAXIMA';

   IF V_COUNT = 0 THEN
      INSERT INTO TDDCAM( NUCAMPO
                        , NOMETAB
                        , NOMECAMPO
                        , DESCRCAMPO
                        , TIPCAMPO
                        , MASCARA
                        , EXPRESSAO
                        , PERMITEPESQUISA
                        , CALCULADO
                        , PERMITEPADRAO
                        , APRESENTACAO
                        , ORDEM
                        , VISIVELGRIDPESQUISA
                        , TIPOAPRESENTACAO
                        , SISTEMA
                        , ADICIONAL )
      VALUES ( ( SELECT MAX( NUCAMPO ) + 1
                  FROM TDDCAM
                 WHERE NUCAMPO < 9999990000 )
             , 'TGFGRU'
             , 'AD_MAXIMA'
             , 'INTEGRA COM A MAXIMA?'
             , 'S'
             , NULL
             , NULL
             , 'S'
             , 'N'
             , 'S'
             , 'N'
             , 100
             , 'S'
             , 'O'
             , NULL
             , 'S' );

      INSERT INTO TDDOPC( NUCAMPO, VALOR, OPCAO )
      VALUES ( ( SELECT NUCAMPO
                  FROM TDDCAM
                 WHERE NOMETAB = 'TGFGRU'
                   AND NOMECAMPO = 'AD_MAXIMA' )
             , 'N'
             , 'NAO' );

      INSERT INTO TDDOPC( NUCAMPO, VALOR, OPCAO )
      VALUES ( ( SELECT NUCAMPO
                  FROM TDDCAM
                 WHERE NOMETAB = 'TGFGRU'
                   AND NOMECAMPO = 'AD_MAXIMA' )
             , 'S'
             , 'SIM' );
   END IF;
END;
/

/*
NomeObjeto: AD_MAXIMA_TIPOVENDA
TipoObjeto: COLUMN
NomeTabela: TGFTOP
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFTOP ADD AD_MAXIMA_TIPOVENDA INT
/

/*
NomeObjeto: DH_MAXIMA_NUVEM
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD DH_MAXIMA_NUVEM DATE
/

/*
NomeObjeto: DH_MAXIMA_LANCAMENTO
TipoObjeto: COLUMN
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TGFCAB ADD DH_MAXIMA_LANCAMENTO DATE
/

/*
NomeObjeto: CODGRUPOTRIBUT
TipoObjeto: COLUMN
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TRIBUTACAO_MAXIMA ADD CODGRUPOTRIBUT NUMBER(10)
/

/*
NomeObjeto: PERDIFERIMENTOICMS
TipoObjeto: COLUMN
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TRIBUTACAO_MAXIMA ADD PERDIFERIMENTOICMS FLOAT
/

/*
NomeObjeto: SITTRIBUTPF
TipoObjeto: COLUMN
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

ALTER TABLE TRIBUTACAO_MAXIMA ADD SITTRIBUTPF NUMBER(5)
/

/*
NomeObjeto: AD_ENVIARMAXIMA
TipoObjeto: PROCEDURE
NomeTabela: TGFTOP
Executar  : SEMPRE
*/ 

BEGIN
   IF SNK_COLUNA_EXISTE( 'TGFTOP', 'AD_ENVIARMAXIMA') = 0 THEN
     EXECUTE IMMEDIATE 'ALTER TABLE TGFTOP ADD AD_ENVIARMAXIMA CHAR(1) DEFAULT ''N'' NOT NULL';

     EXECUTE IMMEDIATE 'UPDATE TGFTOP SET AD_ENVIARMAXIMA = ''S'' WHERE AD_MAXIMAORIGEMPD IS NOT NULL';
   END IF;
END;
/

/*
NomeObjeto: DROP - AD_MAXIMA_PROGRESS_BAR
TipoObjeto: TABLE
NomeTabela: AD_MAXIMA_PROGRESS_BAR
Executar  : SE_EXISTIR
*/ 

DROP TABLE AD_MAXIMA_PROGRESS_BAR
/

/*
NomeObjeto: CRIAR PARAMETRO TITTITPADRAOMAX
TipoObjeto: PROCEDURE
NomeTabela: TSIPAR
Executar  : SEMPRE
*/ 

DECLARE
   V_COUNT   INT;
BEGIN
   SELECT COUNT( 1 )
     INTO V_COUNT
     FROM TSIPAR
    WHERE CHAVE = 'TITTITPADRAOMAX';

   IF V_COUNT = 0 THEN
      INSERT INTO TSIPAR( CHAVE
                        , DESCRICAO
                        , CODUSU
                        , TIPO
                        , MODULO
                        , CLASSE
                        , ABA
                        , LOGICO
                        , INTEIRO )
      VALUES ( 'TITTITPADRAOMAX'
             , 'Tipo de Titulo Padrao Maxima'
             , 0
             , 'T'
             , 'E'
             , 'Geral'
             , 'Geral'
             , 'N'
             , NULL );
   END IF;
END;
/

/*
NomeObjeto: SEQUENCE_LOG_MAXIMA
TipoObjeto: PROCEDURE
NomeTabela: AD_LOGMAXIMA
Executar  : SEMPRE
*/ 

DECLARE
   V_SELECAO   NUMBER;
BEGIN
   SELECT 1
     INTO V_SELECAO
     FROM USER_OBJECTS
    WHERE OBJECT_NAME = 'SEQUENCE_LOG_MAXIMA';
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      EXECUTE IMMEDIATE 'CREATE SEQUENCE SEQUENCE_LOG_MAXIMA
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 20
  NOORDER';
END;
/

/*
NomeObjeto: SEQUENCE_ERRO_MAXIMA
TipoObjeto: PROCEDURE
NomeTabela: SEQUENCE_ERRO_MAXIMA
Executar  : SEMPRE
*/ 

DECLARE
   V_SELECAO   NUMBER;
BEGIN
   SELECT 1
     INTO V_SELECAO
     FROM USER_OBJECTS
    WHERE OBJECT_NAME = 'SEQUENCE_ERRO_MAXIMA';
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      EXECUTE IMMEDIATE 'CREATE SEQUENCE SEQUENCE_ERRO_MAXIMA
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 20
  NOORDER';
END;
/

/*
NomeObjeto: SQ_MAXIMA_CAIXA
TipoObjeto: PROCEDURE
NomeTabela: SQ_MAXIMA_CAIXA
Executar  : SEMPRE
*/ 

DECLARE
   V_SELECAO   NUMBER;
BEGIN
   SELECT 1
     INTO V_SELECAO
     FROM USER_OBJECTS
    WHERE OBJECT_NAME = 'SQ_MAXIMA_CAIXA';
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      EXECUTE IMMEDIATE 'CREATE SEQUENCE SQ_MAXIMA_CAIXA
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 20
  NOORDER';
END;
/

/*
NomeObjeto: MERGE_AD_MAXIMAORIGEMPD
TipoObjeto: PROCEDURE
NomeTabela: TGFTOP
Executar  : SEMPRE
*/ 

DECLARE
BEGIN
   MERGE INTO TGFTOP TOP
    USING (SELECT CODTIPOPER, DHALTER
             FROM TGFTOP TOP
            WHERE AD_MAXIMA_TIPOVENDA IS NOT NULL
              AND AD_MAXIMAORIGEMPD IS NULL
              AND DHALTER = (SELECT MAX( DHALTER )
                               FROM TGFTOP T
                              WHERE T.CODTIPOPER = TOP.CODTIPOPER)) T
       ON ( TOP.CODTIPOPER = T.CODTIPOPER
       AND TOP.DHALTER = T.DHALTER )
   WHEN MATCHED THEN
      UPDATE SET AD_MAXIMAORIGEMPD = 'F';
END;
/

/*
NomeObjeto: SQ_MAXIMA_MOV_CAIXA
TipoObjeto: PROCEDURE
NomeTabela: SQ_MAXIMA_MOV_CAIXA
Executar  : SEMPRE
*/ 

DECLARE
   V_SELECAO   NUMBER;
BEGIN
   SELECT 1
     INTO V_SELECAO
     FROM USER_OBJECTS
    WHERE OBJECT_NAME = 'SQ_MAXIMA_MOV_CAIXA';
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      EXECUTE IMMEDIATE 'CREATE SEQUENCE SQ_MAXIMA_MOV_CAIXA
  START WITH 1
  MAXVALUE 9999999999999999999999999999
  MINVALUE 1
  NOCYCLE
  CACHE 20
  NOORDER';
END;
/

/*
NomeObjeto: I02_AD_MOVIMENTOCX_MAX
TipoObjeto: INDEX
NomeTabela: AD_MOVIMENTOCX_MAX
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX I02_AD_MOVIMENTOCX_MAX
   ON AD_MOVIMENTOCX_MAX( ID_ERP )
/

/*
NomeObjeto: IDX_AD_MAXIMA_IDFIN_CAIXA
TipoObjeto: INDEX
NomeTabela: TGFFIN
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_IDFIN_CAIXA
   ON TGFFIN( AD_MAXIMA_IDFIN_CAIXA )
/

/*
NomeObjeto: AD_MAXIMA_CARREGAMENTOS_I01
TipoObjeto: INDEX
NomeTabela: AD_MAXIMA_CARREGAMENTOS_I01
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX AD_MAXIMA_CARREGAMENTOS_I01
   ON AD_MAXIMA_CARREGAMENTOS( CODVEND )
/

/*
NomeObjeto: AD_MAXIMA_CARREGAMENTOS_I02
TipoObjeto: INDEX
NomeTabela: AD_MAXIMA_CARREGAMENTOS_I02
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX AD_MAXIMA_CARREGAMENTOS_I02
   ON AD_MAXIMA_CARREGAMENTOS( DTFECHAMENTO )
/

/*
NomeObjeto: IDX_AD_MAXIMA_MENSAGENS_01
TipoObjeto: INDEX
NomeTabela: AD_MAXIMA_MENSAGENS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_MENSAGENS_01
   ON AD_MAXIMA_MENSAGENS( DTMENSAGEM )
/

/*
NomeObjeto: AD_MAXIMA_INTEGRA_I02
TipoObjeto: INDEX
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX AD_MAXIMA_INTEGRA_I02
   ON AD_MAXIMA_INTEGRA( MD5 )
/

/*
NomeObjeto: AD_INSTANCIA_ACAO_MAXIMA_I01
TipoObjeto: INDEX
NomeTabela: AD_INSTANCIA_ACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE UNIQUE INDEX AD_INSTANCIA_ACAO_MAXIMA_I01
   ON AD_INSTANCIA_ACAO_MAXIMA( ID_INSTANCIA, NUAAG )
/

/*
NomeObjeto: AD_MAXIMA_INTEGRA_I01
TipoObjeto: INDEX
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE UNIQUE INDEX AD_MAXIMA_INTEGRA_I01
   ON AD_MAXIMA_INTEGRA( CHAVE, TIPO )
/

/*
NomeObjeto: TRIBUTACAO_MAXIMA_I01
TipoObjeto: INDEX
NomeTabela: TRIBUTACAO_MAXIMA
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX TRIBUTACAO_MAXIMA_I01
   ON TRIBUTACAO_MAXIMA( CODPROD
                       , CODCLI
                       , UFDESTINO
                       , CODFILIALNF
                       , CODOPER
                       , CONSUMIDOR )
/

/*
NomeObjeto: IDX_AD_MAXIMA_PEDIDO
TipoObjeto: INDEX
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_PEDIDO
   ON TGFCAB( AD_MAXIMA_PEDIDO )
/

/*
NomeObjeto: IDX_AD_MAXIMA_NUMCAR
TipoObjeto: INDEX
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_NUMCAR
   ON TGFCAB( AD_MAXIMA_NUMCAR )
/

/*
NomeObjeto: IDX_AD_MAXIMA_IDCX
TipoObjeto: INDEX
NomeTabela: TGFCAI
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_IDCX
   ON TGFCAI( AD_MAXIMA_IDCX )
/

/*
NomeObjeto: IDX_AD_MAXIMA_IDFIN
TipoObjeto: INDEX
NomeTabela: TGFFIN
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_IDFIN
   ON TGFFIN( AD_MAXIMA_IDFIN )
/

/*
NomeObjeto: IDX_AD_MAXIMA_IDMOVBCO
TipoObjeto: INDEX
NomeTabela: TGFMBC
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_IDMOVBCO
   ON TGFMBC( AD_MAXIMA_IDMOVBCO )
/

/*
NomeObjeto: IDX_AD_MAXIMA_IDPEDIDO
TipoObjeto: INDEX
NomeTabela: TGFCAB
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX IDX_AD_MAXIMA_IDPEDIDO
   ON TGFCAB( AD_MAXIMA_IDPEDIDO )
/

/*
NomeObjeto: I01_AD_MOVIMENTOCX_MAX
TipoObjeto: INDEX
NomeTabela: AD_MOVIMENTOCX_MAX
Executar  : SE_NAO_EXISTIR
*/ 

CREATE INDEX I01_AD_MOVIMENTOCX_MAX
   ON AD_MOVIMENTOCX_MAX( NUFIN )
/

/*
NomeObjeto: GET_MAXIMA_NOTA
TipoObjeto: PROCEDURE
NomeTabela: GET_MAXIMA_NOTA
Executar  : SE_EXISTIR
*/ 

DROP FUNCTION GET_MAXIMA_NOTA
/

/*
NomeObjeto: SNK_GET_NOTA_MAXIMA
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_NOTA_MAXIMA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_NOTA_MAXIMA( P_NUNOTA INT )
   RETURN INT AS
   /* funcao recebe o NUNOTA do pedido e procura a nota recursivamente 
      se não encontrar NOTA retorna ZERO */  
  V_RESULT INT;
  V_TIPMOV CHAR(1);
BEGIN
   V_RESULT := 0;
    
   --percorrendo as ligações pela TGFVAR
   FOR LIGACAO IN ( SELECT DISTINCT V.NUNOTA
                     FROM TGFVAR V
                    WHERE V.NUNOTAORIG <> V.NUNOTA AND V.NUNOTAORIG = P_NUNOTA ) LOOP

      --obtendo o TIPMOV da ligação 
      SELECT MAX(TIPMOV)
      INTO V_TIPMOV
      FROM TGFCAB
      WHERE NUNOTA = LIGACAO.NUNOTA;


      --se ligado com nota, seta o NUNOTA
      IF V_TIPMOV = 'V' THEN 
        V_RESULT := LIGACAO.NUNOTA;
      -- se ligado com pedido, chama novamente recursivamente 
      ELSIF V_TIPMOV = 'P' THEN 
        V_RESULT := SNK_GET_NOTA_MAXIMA( LIGACAO.NUNOTA );
      END IF;
      
      --se achou a nota, retorna
      IF V_RESULT <> 0 THEN
        RETURN V_RESULT;
      END IF;


   END LOOP;
   
   RETURN V_RESULT;
   
END;
/

/*
NomeObjeto: SNK_GET_PD_MAXIMA
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_PD_MAXIMA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_PD_MAXIMA( P_NUNOTA INT )
   RETURN INT AS
   /* funcao recebe o NUNOTA da NOTA e procura o pedido recursivamente 
      se não encontrar o pedido retorna ZERO */  
  V_RESULT INT;
  V_TIPMOV CHAR(1);
BEGIN
   V_RESULT := 0;
   --percorrendo as ligações pela TGFVAR
   FOR LIGACAO IN ( SELECT DISTINCT V.NUNOTAORIG 
                     FROM TGFVAR V
                    WHERE V.NUNOTA = P_NUNOTA ) LOOP

      --obtendo o TIPMOV da ligação 
      SELECT MAX(CAB.TIPMOV)
      INTO V_TIPMOV
      FROM TGFCAB CAB, TGFTOP TOP
      WHERE NUNOTA = LIGACAO.NUNOTAORIG
      AND CAB.DHTIPOPER = TOP.DHALTER
      AND CAB.CODTIPOPER = TOP.CODTIPOPER
      AND TOP.AD_ENVIARMAXIMA = 'S';
      --se ligado com nota, seta o NUNOTA
      IF V_TIPMOV = 'P' THEN 
        V_RESULT := SNK_GET_PD_MAXIMA( LIGACAO.NUNOTAORIG );
        --se não achou outro pedido
        IF V_RESULT = 0 THEN
          V_RESULT := LIGACAO.NUNOTAORIG;
        END IF;
      END IF;
      --se achou a nota, retorna
      IF V_RESULT <> 0 THEN
        RETURN V_RESULT;
      END IF;
   END LOOP;
   RETURN V_RESULT;
END;
/

/*
NomeObjeto: SNK_GET_CAB_MAXIMA_EXISTE
TipoObjeto: FUNCTION
NomeTabela: TGFCAB
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_CAB_MAXIMA_EXISTE(
   P_IDPEDIDO_MAXIMA    INT
 , P_TIPMOV             CHAR )
   RETURN BOOLEAN AS
   PRAGMA AUTONOMOUS_TRANSACTION;
   P_COUNT   INT;
BEGIN
   SELECT COUNT( 1 )
     INTO P_COUNT
     FROM TGFCAB C, TGFTOP T
    WHERE C.AD_MAXIMA_IDPEDIDO = P_IDPEDIDO_MAXIMA
      AND C.TIPMOV = P_TIPMOV
      AND C.CODTIPOPER = T.CODTIPOPER
      AND C.DHTIPOPER = T.DHALTER
      AND T.AD_ENVIARMAXIMA = 'S';
   RETURN P_COUNT > 0;
END;
/

/*
NomeObjeto: SNK_GET_MD5
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_MD5
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_MD5( VALOR VARCHAR )
   RETURN VARCHAR2 IS
   V_INPUT   VARCHAR2( 4000 ) := VALOR;
   HEXKEY    VARCHAR2( 32 ) := NULL;
BEGIN
   HEXKEY :=
      RAWTOHEX(
                DBMS_OBFUSCATION_TOOLKIT.MD5(
                                              INPUT => UTL_RAW.CAST_TO_RAW(
                                                                            V_INPUT ) ) );
   RETURN NVL( HEXKEY, '' );
END;
/

/*
NomeObjeto: SNK_GET_CUSTO
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_CUSTO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_CUSTO( P_TIPOCUSTO   IN VARCHAR2
                                        , P_CODEMP      IN INT
                                        , P_CODPROD     IN INT
                                        , P_CODLOCAL       INT
                                        , P_CONTROLE    IN VARCHAR2
                                        , P_DTREF          DATE )
   RETURN NUMBER IS
   /************************************************************************************************
   NOME AUTOR: Sankhya Gestao de Negocios
   MD5 AUTOR:  b03d23cb0a5ddddbc7be94607f2ddd19
   DATA......: 24/03/2017
   OBJETIVO..: Funcao que retorna o custo de um produto de acordo com os parametros passados.
                     eh possivel retornar qualquer um dos 6 custos existentes ( ver parametro P_TIPOCUSTO abaixo  )

   PARAMETROS DE ENTRADA:
            P_TIPOCUSTO: Tipo de custo que se deseja objter o valor, podendo ser ( MEDIOSEMICMS / MEDIOCOMICMS / MEDIOGERENCIAL / REPOSICAO / VARIAVEL / GERENCIAL )
            P_CODEMP : Empresa da qual se deseja obter o custo, so eh considerado o valor deste parametro se a configuracao do sistema esta usando CUSTOPOREMPRESA ligado.
            P_CODPROD: Produto que se deseja obter o custo.
            P_CODLOCAL: Local do produto que se deseja obter o custo, so eh considerado o valor deste parametro se a configuracao do sistema esta usando CUSTOPORLOCAL ligado.
            P_CONTROLE: Controle do produto que se deseja obter o custo, so eh considerado o valor deste parametro se a configuracao do sistema esta usando CUSTOPORCONTROLE ligado.
            P_DTREF: Data que deseja objter o custo, o custo buscado eh sempre o da maior data que seja menor ou igual a este parametro.

   EXEMPLO DE USO:
               SELECT ITE.CODPROD, SNK_GET_CUSTO( 'MEDIOCOMICMS'  , ITE.CODEMP  , ITE.CODPROD  , ITE.CODLOCALORIG  , ITE.CONTROLE ,CAB.DTNEG ) AS CUSTO
               FROM TGFITE ITE, TGFCAB CAB WHERE CAB.NUNOTA = 23669
               AND ITE.NUNOTA = CAB.NUNOTA
   *************************************************************************************************/  

   P_CUSTO   NUMBER;
   P_TIPO    VARCHAR2( 50 );
BEGIN
   P_TIPO := UPPER( P_TIPOCUSTO );

   IF P_TIPO IS NULL THEN
      RETURN 0;
   END IF;

   IF P_TIPO NOT IN
         ( 'MEDIOSEMICMS'
        , 'MEDIOCOMICMS'
        , 'MEDIOGERENCIAL'
        , 'REPOSICAO'
        , 'VARIAVEL'
        , 'GERENCIAL'
        , 'ENTRADACOMICMS' ) THEN
      RAISE_APPLICATION_ERROR(
                               -20101
                             , 'TIPO DE CUSTO [' || P_TIPO ||
                               '] INVALIDO PASSADO COMO PARAMETRO PARA A FUNCAO SNK_GET_CUSTO' );
   END IF;

   SELECT CASE
             WHEN P_TIPO = 'MEDIOSEMICMS' THEN
                NVL( MAX( CUSMEDICM ), 0 )
             WHEN P_TIPO = 'MEDIOCOMICMS' THEN
                NVL( MAX( CUSSEMICM ), 0 )
             WHEN P_TIPO = 'MEDIOGERENCIAL' THEN
                NVL( MAX( CUSMED ), 0 )
             WHEN P_TIPO = 'REPOSICAO' THEN
                NVL( MAX( CUSREP ), 0 )
             WHEN P_TIPO = 'VARIAVEL' THEN
                NVL( MAX( CUSVARIAVEL ), 0 )
             WHEN P_TIPO = 'GERENCIAL' THEN
                NVL( MAX( CUSGER ), 0 )
             WHEN P_TIPO = 'ENTRADACOMICMS' THEN
                NVL( MAX( ENTRADACOMICMS ), 0 )
          END
             AS CUSTO
     INTO P_CUSTO
     FROM TGFCUS
    WHERE CODPROD = P_CODPROD
      AND ( VARIAVEIS_PKG.V_CUSTOPOREMPRESA = 'N'
        OR VARIAVEIS_PKG.V_CUSTOPOREMPRESA = 'S'
       AND CODEMP = P_CODEMP )
      AND ( VARIAVEIS_PKG.V_CUSTOPORLOCAL = 'N'
        OR VARIAVEIS_PKG.V_CUSTOPORLOCAL = 'S'
       AND CODLOCAL = P_CODLOCAL )
      AND ( VARIAVEIS_PKG.V_CUSTOPORCONTROLE = 'N'
        OR VARIAVEIS_PKG.V_CUSTOPORCONTROLE = 'S'
       AND CONTROLE = P_CONTROLE )
      AND DTATUAL = (SELECT MAX( C.DTATUAL )
                       FROM TGFCUS C
                      WHERE C.CODPROD = P_CODPROD
                        AND ( VARIAVEIS_PKG.V_CUSTOPOREMPRESA = 'N'
                          OR VARIAVEIS_PKG.V_CUSTOPOREMPRESA = 'S'
                         AND CODEMP = P_CODEMP )
                        AND ( VARIAVEIS_PKG.V_CUSTOPORLOCAL = 'N'
                          OR VARIAVEIS_PKG.V_CUSTOPORLOCAL = 'S'
                         AND CODLOCAL = P_CODLOCAL )
                        AND ( VARIAVEIS_PKG.V_CUSTOPORCONTROLE = 'N'
                          OR VARIAVEIS_PKG.V_CUSTOPORCONTROLE = 'S'
                         AND CONTROLE = P_CONTROLE )
                        AND C.DTATUAL <= P_DTREF);

   RETURN P_CUSTO;
END;
/

/*
NomeObjeto: SNK_GET_PRECO
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_PRECO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_PRECO( P_NUTAB      INT
                                        , P_CODPROD    INT
                                        , P_DTVIGOR    DATE )
   RETURN FLOAT IS
   TROCA              INT;
   P_CODTAB           TGFTAB.CODTAB%TYPE;
   P_CODTABORIG       TGFTAB.CODTAB%TYPE;
   P_DECVLR           TGFPRO.DECVLR%TYPE;
   P_CODGRUPOPROD     TGFPRO.CODGRUPOPROD%TYPE;
   P_COMVEND          TGFPRO.COMVEND%TYPE;
   P_COMGER           TGFPRO.COMGER%TYPE;
   P_MARGLUCRO        TGFPRO.MARGLUCRO%TYPE;
   P_ESTMAX           TGFPRO.ESTMAX%TYPE;
   P_COUNT            INT;
   P_TIPO             CHAR;
   P_VALOR            FLOAT;
   P_PERCEN           FLOAT;
   P_MULTIP           FLOAT;
   P_CUSFIX           FLOAT;
   P_PERCGRUPO        FLOAT;
   P_DTVIGORAUX       DATE;
   P_SEMPRE           CHAR;


   P_ATIVO            CHAR( 1 );
   P_UTILZADECCUSTO   CHAR( 1 );
   P_CUSTODEC         NUMBER( 10 );
   P_PRECO            FLOAT;
BEGIN
   -- QDO BUSCAR UM NUTAB P/UM CODTAB QUE NAO TIVER EXCECAO DE PRECO POR ELE BUSCAR A TABELA DE ORIGEM E NAO O NUTAB ANTERIOR DA MESMA TABELA.

    /*
     MARCELO    : 11/12/2002
     OBSERVACAO : TEM PERSONALIZACOES PARA O COCAL, QUANDO FOR MEXER NESSA PROCE
DURE LEMBRAR

                  DE ELIMINAR O COMENTARIO PARA A COCAL. E JUNCO
    */  
   P_VALOR := 0;

   P_CUSTODEC := GET_TSIPAR_INTEIRO( 'CUSTODEC' );


   BEGIN
      SELECT NTA.ATIVO, NVL( TAB.CODTABORIG, TAB.CODTAB ), TAB.CODTAB
        INTO P_ATIVO, P_CODTABORIG, P_CODTAB
        FROM TGFTAB TAB, TGFNTA NTA
       WHERE TAB.NUTAB = P_NUTAB
         AND TAB.CODTAB = NTA.CODTAB;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         RETURN P_PRECO;
   END;


   IF ( P_ATIVO = 'N' ) THEN
      RETURN P_PRECO;
   END IF;

   BEGIN
      SELECT NVL( DECVLR, 2 )
           , COMVEND
           , COMGER
           , MARGLUCRO
           , ESTMAX
           , CODGRUPOPROD
        INTO P_DECVLR
           , P_COMVEND
           , P_COMGER
           , P_MARGLUCRO
           , P_ESTMAX
           , P_CODGRUPOPROD
        FROM TGFPRO
       WHERE CODPROD = P_CODPROD
         AND CODPROD <> 0;
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         RETURN P_PRECO;
   END;

   P_DTVIGORAUX := P_DTVIGOR;

   IF ( P_DTVIGOR IS NULL ) THEN
      P_DTVIGORAUX := SYSDATE( );
   END IF;

   P_SEMPRE := 'S';
   P_MULTIP := 0;

   TROCA := P_NUTAB;

   -- COM ESTE TECHO, NAO PODE EXCLUIR PRODUTO, TEM QUE INCLUIR PRECO ZERO. SE APAGAR UM PRECO, O PRECO ANTERIOR VOLTA.

   -- SEM ISTO, TODOS OSPRODUTOS DE TABORIG=TAB TEM QUE SER COPIADOS PARA A NOVA TABELA. ISTO PERMITE EXCLUIR PRODUTOS, JA QUE O ULTIMO NAO SERA APRESENTADO.

   /* IF P_CODTABORIG = P_CODTAB AND P_CODTAB <> 0 THEN
      SELECT COUNT (1)
        INTO P_COUNT
        FROM TGFEXC E
       WHERE E.NUTAB = TROCA
         AND E.CODPROD = P_CODPROD;

      IF P_COUNT = 0 THEN
        SELECT NVL(MAX (M.NUTAB), -999999)
        INTO TROCA
        FROM TGFTAB M, TGFEXC E
        WHERE M.DTVIGOR <= P_DTVIGORAUX
        AND M.CODTAB = P_CODTAB
        AND E.CODPROD = P_CODPROD
        AND E.NUTAB = M.NUTAB;
      END IF;
    END IF; */  

   WHILE ( P_SEMPRE = 'S' ) LOOP
      BEGIN
         SELECT NVL( PERCENTUAL, 0 )
              , NVL( CODTABORIG, CODTAB )
              , CODTAB
              , UTILIZADECCUSTO
           INTO P_PERCEN
              , P_CODTABORIG
              , P_CODTAB
              , P_UTILZADECCUSTO
           FROM TGFTAB
          WHERE NUTAB = TROCA;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            TROCA := TROCA;
      END;


      IF P_UTILZADECCUSTO = 'S' THEN
         IF P_CUSTODEC <> 0 THEN
            P_DECVLR := P_CUSTODEC;
         ELSE
            P_DECVLR := 2;
         END IF;
      END IF;

      /* INICIO DESCOMENTAR QUANDO MANDAR PARA O COCAL
      SELECT
       NVL(COUNT(1),0)
      INTO

       P_COUNT
      FROM
       TGFTBG
      WHERE CODTAB = P_CODTAB AND CODGRUPOPROD = P_CODGRUPOPROD;
      IF ((P_COUNT<>0) AND (P_CODTAB <> 0) AND (P_CODGRUPOPROD <> 0)) THEN
          BEGIN
            SELECT
             NVL(PERCENTUAL, -999999)
            INTO
             P_PERCGRUPO
            FROM
             TGFTBG
            WHERE CODTAB = P_CODTAB AND CODGRUPOPROD = P_CODGRUPOPROD;

            P_PERCEN := P_PERCGRUPO;
          EXCEPTION WHEN NO_DATA_FOUND THEN
            P_PERCEN := 0;
          END;
         P_CODGRUPOPROD := 0;
      END IF;
      FIM */  
      SELECT COUNT( 1 )
        INTO P_COUNT
        FROM TGFEXC E
       WHERE E.NUTAB = TROCA
         AND E.CODPROD = P_CODPROD;


      IF ( P_COUNT > 0 ) THEN /* SE A TABELA TEM EXCECAO */  
         SELECT MAX( E.TIPO ), MAX( E.VLRVENDA )
           INTO P_TIPO, P_VALOR
           FROM TGFEXC E
          WHERE E.NUTAB = TROCA
            AND E.CODPROD = P_CODPROD;

         IF ( P_TIPO = 'P' )
        AND ( P_CODTABORIG <> P_CODTAB ) THEN /* SE A EXC. E POR PERC. E  A TAB. TEM ORIGEM */  
            P_MULTIP := P_MULTIP + ( P_VALOR / 100.0000 );


            SELECT NVL( MAX( M.NUTAB ), -999999 )
              INTO TROCA
              FROM TGFTAB M, TGFEXC E
             WHERE E.NUTAB = M.NUTAB
               AND M.CODTAB = P_CODTABORIG
               AND E.CODPROD = P_CODPROD
               AND M.DTVIGOR = (SELECT MAX( M2.DTVIGOR )
                                  FROM TGFTAB M2, TGFEXC E2
                                 WHERE M2.DTVIGOR <= P_DTVIGORAUX
                                   AND M2.CODTAB = P_CODTABORIG
                                   AND E2.CODPROD = P_CODPROD
                                   AND E2.NUTAB = M2.NUTAB);


            IF ( TROCA = -999999 ) THEN
               /*MARCELO PARA FICAR IGUAL AO SQL*/  
               SELECT NVL( MAX( M.NUTAB ), -999999 )
                 INTO TROCA
                 FROM TGFTAB M
                WHERE M.DTVIGOR <= P_DTVIGORAUX
                  AND M.CODTAB = P_CODTABORIG;

               IF ( TROCA = -999999 ) THEN
                  P_PRECO := 0;
                  P_SEMPRE := 'N';
               /* PRINT 'SAIU NO P' */  
               END IF;
            END IF;
         ELSE /* SENAO A EXECECAO E POR VALOR */  
            IF ( P_MULTIP <> 0 ) THEN
               P_PRECO := ROUND( P_VALOR + ( P_VALOR * P_MULTIP ), P_DECVLR );
            ELSE
               P_PRECO := ROUND( P_VALOR, P_DECVLR );
            END IF;

            P_SEMPRE := 'N';
         /* PRINT 'SAIU NO ACHOU' */  
         END IF;
      ELSIF ( P_CODTAB = 0 ) THEN
         /* PRINT 'TAB 0' */  

         SELECT NVL( MAX( M.NUTAB ), -999999 )
           INTO TROCA
           FROM TGFTAB M, TGFEXC E
          WHERE E.NUTAB = M.NUTAB
            AND M.CODTAB = 0
            AND E.CODPROD = P_CODPROD
            AND M.DTVIGOR = (SELECT MAX( M2.DTVIGOR )
                               FROM TGFTAB M2, TGFEXC E2
                              WHERE M2.DTVIGOR <= P_DTVIGORAUX
                                AND M2.CODTAB = 0
                                AND E2.CODPROD = P_CODPROD
                                AND E2.NUTAB = M2.NUTAB);

         IF ( TROCA = -999999 ) THEN
            P_PRECO := 0;
            P_SEMPRE := 'N';
         END IF;
      ELSIF ( P_CODTABORIG = P_CODTAB ) THEN
         /* CHEGOU NO ULT. NIVEL E NAO ACHOU EXCECAO */  
         P_PRECO := 0;
         P_SEMPRE := 'N';
      /* PRINT 'TAB IGUAIS' */  
      ELSE
         P_MULTIP := P_MULTIP + ( P_PERCEN / 100.0000 );


         /*      SELECT NVL (MAX (M.NUTAB), -999999)
                   INTO TROCA
                   FROM TGFTAB M, TGFEXC E
                  WHERE M.DTVIGOR <= P_DTVIGORAUX
                    AND M.CODTAB = P_CODTAB
                    AND E.CODPROD = P_CODPROD
                    AND E.NUTAB = M.NUTAB;

                 IF TROCA = -999999 THEN
         */  


         SELECT NVL( MAX( M.NUTAB ), -999999 )
           INTO TROCA
           FROM TGFTAB M
          WHERE M.DTVIGOR <= P_DTVIGORAUX
            AND M.CODTAB = P_CODTABORIG;

         IF ( TROCA = -999999 ) THEN
            P_PRECO := 0;
            P_SEMPRE := 'N';
         ELSE
            SELECT NVL( CODTABORIG, CODTAB ), CODTAB
              INTO P_CODTABORIG, P_CODTAB
              FROM TGFTAB
             WHERE NUTAB = TROCA;

            IF ( P_CODTABORIG = P_CODTAB ) THEN
               SELECT NVL( MAX( M.NUTAB ), -999999 )
                 INTO TROCA
                 FROM TGFTAB M, TGFEXC E
                WHERE E.NUTAB = M.NUTAB
                  AND M.CODTAB = P_CODTAB
                  AND E.CODPROD = P_CODPROD
                  AND M.DTVIGOR = (SELECT MAX( M2.DTVIGOR )
                                     FROM TGFTAB M2, TGFEXC E2
                                    WHERE M2.DTVIGOR <= P_DTVIGORAUX
                                      AND M2.CODTAB = P_CODTAB
                                      AND E2.CODPROD = P_CODPROD
                                      AND E2.NUTAB = M2.NUTAB);

               IF ( TROCA = -999999 ) THEN
                  P_PRECO := 0;
                  P_SEMPRE := 'N';
               END IF;
            END IF;
         END IF;
      --OS 792484
      --PRECISA ZERAR O MULTIPLICADOR QUANDO ENCONTRA PRECO EM UMA EXCECAO DO MESMO CODTAB

      /*      ELSE
                P_MULTIP := 0;
              END IF;
      */  
      END IF;
   END LOOP;


   RETURN P_PRECO;
END;
/

/*
NomeObjeto: SNK_GET_PROXIMO_CODIGO
TipoObjeto: FUNCTION
NomeTabela: SNK_GET_PROXIMO_CODIGO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE FUNCTION SNK_GET_PROXIMO_CODIGO( P_ARQUIVO   IN VARCHAR
                                                 , P_CODEMP    IN INT
                                                 , P_TABELA    IN VARCHAR
                                                 , P_CAMPO     IN VARCHAR )
   RETURN NUMBER AS
   P_ULTCOD   NUMBER;
   P_DSYNC    NUMBER;
BEGIN
   SELECT COUNT( 1 ) AS QTD INTO P_DSYNC FROM TSDPAR;

   STP_KEYGEN_TGFNUM( P_ARQUIVO
                    , P_CODEMP
                    , P_TABELA
                    , P_CAMPO
                    , P_DSYNC
                    , P_ULTCOD );
   RETURN P_ULTCOD;
END;
/

/*
NomeObjeto: STP_OBTEM_PRECO2
TipoObjeto: PROCEDURE
NomeTabela: STP_OBTEM_PRECO2
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_OBTEM_PRECO2( P_NUTAB         INT
                                            , P_CODPROD       INT
                                            , P_DTVIGOR       DATE
                                            , P_PRECO     OUT FLOAT ) AS
BEGIN
   P_PRECO := SNK_GET_PRECO( P_NUTAB, P_CODPROD, P_DTVIGOR );
END;
/

/*
NomeObjeto: STP_TRIBUTACAO_MAXIMA
TipoObjeto: PROCEDURE
NomeTabela: STP_TRIBUTACAO_MAXIMA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_TRIBUTACAO_MAXIMA AS
   QTDTOTALPARC   INT;
   V_TIPOVENDA    INT;
BEGIN
   /* LIMPANDO A TABELA DE TRIBUTACAO MAXIMA */  
   EXECUTE IMMEDIATE 'TRUNCATE TABLE TRIBUTACAO_MAXIMA';

   SELECT CASE WHEN COUNT( 1 ) > 0 THEN 14 ELSE 1 END
     INTO V_TIPOVENDA
     FROM TGFTOP T
    WHERE T.AD_MAXIMA_TIPOVENDA = 14
      AND T.DHALTER = (SELECT MAX( T2.DHALTER )
                         FROM TGFTOP T2
                        WHERE T2.CODTIPOPER = T.CODTIPOPER);

   /* INSERINDO TRIBUTACAO PADRAO ( SEM RESTRICAO ) */  
   INSERT INTO TRIBUTACAO_MAXIMA
   (   IDLINHA 
      , CODEMP 
      , CODPROD
      , CODFILIALNF
      , UFDESTINO 
      , CODOPER 
      , CODCLI 
      , AGREGARIPICALCULOST
      , ALIQICMS1 
      , ALIQICMS1FONTE
      , ALIQICMS2 
      , ALIQICMS2FONTE
      , CODICM 
      , CODICMPF
      , CODICMPRODRURAL
      , CODICMTAB 
      , CODICMTABPF
      , IVA 
      , IVAFONTE
      , MOSTRARPVENDASEMIPI
      , MOSTRARPVENDASEMST 
      , OBS
      , PAUTA
      , PERACRESCIMOPF 
      , PERBASEREDNRPA 
      , PERCACRESICMSPF_PI
      , PERCBASERED 
      , CONSUMIDOR 
      , TIPOSN 
      , PERCBASEREDST
      , PERCBASEREDSTFONTE
      , PERCBASESTRJ 
      , PERCDESCCOFINS
      , PERCDESCPIS 
      , PERDESCICMISENCAO
      , PERDESCPISSUFRAMA
      , PERDESCREPASSE 
      , PERDESCSUFRAMA
      , RIOLOGISENTOST 
      , SITTRIBUT 
      , SITTRIBUTPF
      , TIPOCALCULOGNRE
      , TV9ISENTOST 
      , USAVALORULTENTBASEST
      , USAVALORULTENTBASEST2
      , USAVLULTENTMEDIOBASEST
      , UTILIZAPERCBASEREDPF 
      , CODFISCALVENDAPRONTAENT
      , CODFISCALVENDAPRONTAENTINTER
      , CODFISCALBONIFIC 
      , CODFISCALBONIFICINTER
      , PRIORIDADE 
      , PERCBASEREDCONSUMIDOR
      , PERCREDPVENDASIMPLESNAC
      , PERDIFERIMENTOICMS 
      , CODGRUPOTRIBUT
      , ALIQICMSFECP
      , PERACRESCIMOFUNCEP
      )
      SELECT ROWNUM AS IDLINHA, T.*
        FROM (SELECT DISTINCT
                     CASE
                        WHEN NVL( CODEMP, 0 ) = 0 THEN
                           ( SELECT NVL( MIN( CODEMPBASE ), 1 )
                              FROM AD_MAXCONF )
                        ELSE
                           CODEMP
                     END
                        AS CODEMP
                   , NVL( CODPROD, 0 ) AS CODPROD
                   , CASE
                        WHEN NVL( CODFILIALNF, 0 ) = 0 THEN 1
                        ELSE CODFILIALNF
                     END
                        AS CODFILIALNF
                   , NVL( UFDESTINO, ' ' ) AS UFDESTINO
                   , NVL( CODOPER, 0 ) AS CODOPER
                   , NVL( CODCLI, 0 ) AS CODCLI
                   , NVL( AGREGARIPICALCULOST, 'N' ) AS AGREGARIPICALCULOST
                   , NVL( ALIQICMS1, 0 ) AS ALIQICMS1
                   , NVL( ALIQICMS1FONTE, 0 ) AS ALIQICMS1FONTE
                   , NVL( ALIQICMS2, 0 ) AS ALIQICMS2
                   , NVL( ALIQICMS2FONTE, 0 ) AS ALIQICMS2FONTE
                   , NVL( CODICM, 0 ) AS CODICM
                   , NVL( CODICMPF, 0 ) AS CODICMPF
                   , NVL( CODICMPRODRURAL, 0 ) AS CODICMPRODRURAL
                   , NVL( CODICMTAB, 0 ) AS CODICMTAB
                   , NVL( CODICMTABPF, 0 ) AS CODICMTABPF
                   , NVL( IVA, 0 ) AS IVA
                   , NVL( IVAFONTE, 0 ) AS IVAFONTE
                   , NVL( MOSTRARPVENDASEMIPI, 'N' ) AS MOSTRARPVENDASEMIPI
                   , NVL( MOSTRARPVENDASEMST, 'N' ) AS MOSTRARPVENDASEMST
                   , NVL( OBS, ' ' ) AS OBS
                   , NVL( PAUTA, 0 ) AS PAUTA
                   , NVL( PERACRESCIMOPF, 0 ) AS PERACRESCIMOPF
                   , NVL( PERBASEREDNRPA, 0 ) AS PERBASEREDNRPA
                   , NVL( PERCACRESICMSPF_PI, 0 ) AS PERCACRESICMSPF_PI
                   , NVL( PERCBASERED, 0 ) AS PERCBASERED
                   , NVL( CONSUMIDOR, 'N' ) AS CONSUMIDOR
                   , NVL( TIPOSN, 0 ) AS TIPOSN
                   , NVL( PERCBASEREDST, 0 ) AS PERCBASEREDST
                   , NVL( PERCBASEREDSTFONTE, 0 ) AS PERCBASEREDSTFONTE
                   , NVL( PERCBASESTRJ, 0 ) AS PERCBASESTRJ
                   , NVL( PERCDESCCOFINS, 0 ) AS PERCDESCCOFINS
                   , NVL( PERCDESCPIS, 0 ) AS PERCDESCPIS
                   , NVL( PERDESCICMISENCAO, 0 ) AS PERDESCICMISENCAO
                   , NVL( PERDESCPISSUFRAMA, 0 ) AS PERDESCPISSUFRAMA
                   , NVL( PERDESCREPASSE, 0 ) AS PERDESCREPASSE
                   , NVL( PERDESCSUFRAMA, 0 ) AS PERDESCSUFRAMA
                   , NVL( RIOLOGISENTOST, 0 ) AS RIOLOGISENTOST
                   , NVL( SITTRIBUT, 0 ) AS SITTRIBUT
                   , NVL( SITTRIBUTPF, SITTRIBUT ) AS SITTRIBUTPF
                   , NVL( TIPOCALCULOGNRE, 'P' ) AS TIPOCALCULOGNRE
                   , NVL( TV9ISENTOST, 0 ) AS TV9ISENTOST
                   , NVL( USAVALORULTENTBASEST, 'N' ) AS USAVALORULTENTBASEST
                   , NVL( USAVALORULTENTBASEST2, 'N' )
                        AS USAVALORULTENTBASEST2
                   , NVL( USAVLULTENTMEDIOBASEST, 'N' )
                        AS USAVLULTENTMEDIOBASEST
                   , NVL( UTILIZAPERCBASEREDPF, 0 ) AS UTILIZAPERCBASEREDPF
                   , NVL( CODFISCALVENDAPRONTAENT, 0 )
                        AS CODFISCALVENDAPRONTAENT
                   , NVL( CODFISCALVENDAPRONTAENTINTER, 0 )
                        AS CODFISCALVENDAPRONTAENTINTER
                   , NVL( CODFISCALBONIFIC, 0 ) AS CODFISCALBONIFIC
                   , NVL( CODFISCALBONIFICINTER, 0 ) AS CODFISCALBONIFICINTER
                   , NVL( PRIORIDADE, 0 ) AS PRIORIDADE
                   , NVL( PERCBASEREDCONSUMIDOR, 0 ) AS PERCBASEREDCONSUMIDOR
                   , NVL( PERCREDPVENDASIMPLESNAC, 0 ) AS PERCREDPVENDASIMPLESNAC
                   , NVL( PERDIFERIMENTOICMS, 0 ) AS PERDIFERIMENTOICMS
                   , NVL( CODGRUPOTRIBUT, 0 ) AS CODGRUPOTRIBUT
                   , NVL( ALIQICMSFECP, 0 ) AS ALIQICMSFECP
                   , NVL( PERACRESCIMOFUNCEP, 0 ) AS PERACRESCIMOFUNCEP
                FROM (SELECT T.*
                           , CASE
                                WHEN T.CONSUMIDOR = 'S' THEN PERCBASERED
                                ELSE 0
                             END
                                AS PERCBASEREDCONSUMIDOR
                           -- % ICMS SIMPLES NACIONAL
                           , ( SELECT PSN.ALIQICMS
                                FROM TGFEMPSN EMPSN, TGFPSN PSN
                               WHERE EMPSN.CODEMP = T.CODEMP
                                 AND PSN.NUPARTILHA = EMPSN.NUPARTILHA
                                 AND ( ( T.TIPOSN = 1
                                    AND PSN.TIPOSN = 1 )
                                   OR ( T.TIPOSN = 2
                                   AND PSN.TIPOSN = 2 )
                                   OR ( T.TIPOSN = 3
                                   AND PSN.TIPOSN IN (3, 4) ) )
                                 AND EMPSN.DTREF =
                                        (SELECT MAX( E1.DTREF )
                                           FROM TGFEMPSN E1, TGFPSN P1
                                          WHERE E1.CODEMP = T.CODEMP
                                            AND P1.NUPARTILHA = E1.NUPARTILHA
                                            AND ( ( T.TIPOSN = 1
                                               AND P1.TIPOSN = 1 )
                                              OR ( T.TIPOSN = 2
                                              AND P1.TIPOSN = 2 )
                                              OR ( T.TIPOSN = 3
                                              AND P1.TIPOSN IN (3, 4) ) )
                                            AND E1.DTREF <= TRUNC( SYSDATE )) )
                                AS PERCREDPVENDASIMPLESNAC
                        FROM (SELECT 0 AS CODEMP
                                   , 0 AS CODPROD
                                   , EMP.CODEMP AS CODFILIALNF
                                   , ( SELECT UF
                                        FROM TSIUFS U
                                       WHERE U.CODUF = ICM.UFDEST )
                                        AS UFDESTINO
                                   , TPO.AD_MAXIMA_TIPOVENDA AS CODOPER
                                   , 0 AS CODCLI
                                   , IPI.IPIINCICMS AS AGREGARIPICALCULOST --Parametro IPIINCICMS
                                   , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS1 --Aliquota de ST Interno
                                   , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS1FONTE --Aliquota de ST Interno
                                   , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS2 --Aliquota de ST Externo
                                   , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS2FONTE --Aliquota de ST Externo
                                   , ICM.ALIQUOTA AS CODICM --Aliquota ICMS para PJ
                                   , ICM.ALIQUOTA AS CODICMPF --Aliquota ICMS para PF
                                   , ICM.ALIQUOTA AS CODICMPRODRURAL
                                   --Aliquota ICMS para Produtor Rural
                                   , ICM.ALIQUOTA AS CODICMTAB --Aliquota ICMS para PJ
                                   , ICM.ALIQUOTA AS CODICMTABPF --Aliquota ICMS para PF
                                   , ICM.MARGLUCRO AS IVA
                                   , ICM.MARGLUCRO AS IVAFONTE
                                   , ICM.PERCSTFCPINT AS ALIQICMSFECP  --Fundo Combate a Pobreza ST
                                   , ICM.PERCICMSFCPINT AS PERACRESCIMOFUNCEP  --Fundo Combate a Pobreza ICMS INTERNO
                                   , 'N' AS MOSTRARPVENDASEMIPI
                                   , 'N' AS MOSTRARPVENDASEMST
                                   , '' AS OBS
                                   , 0 AS PAUTA
                                   , 0 AS PERACRESCIMOPF
                                   , 0 AS PERBASEREDNRPA
                                   , 0 AS PERCACRESICMSPF_PI
                                   , ICM.REDBASE AS PERCBASERED
                                   , 'N' AS CONSUMIDOR
                                   , 0 AS TIPOSN
                                   , ICM.REDBASEST AS PERCBASEREDST
                                   , ICM.REDBASEST AS PERCBASEREDSTFONTE
                                   , 0 AS PERCBASESTRJ
                                   , 0 AS PERCDESCCOFINS
                                   , 0 AS PERCDESCPIS
                                   , 0 AS PERDESCICMISENCAO
                                   , 0 AS PERDESCPISSUFRAMA
                                   , REPPERCBASEICMS AS PERDESCREPASSE
                                   , REDBASEST AS PERDESCSUFRAMA
                                   , 0 AS RIOLOGISENTOST
                                   , ICM.CODTRIB AS SITTRIBUT
                                   , ( SELECT I.CODTRIB
                                        FROM TGFICM I
                                        WHERE I.UFORIG = ICM.UFORIG
                                          AND I.UFDEST = ICM.UFDEST
                                          AND I.TIPRESTRICAO  = 'N'  --CONSUMIDOR
                                          AND I.TIPRESTRICAO2 = 'S'  --SEM EXCEÇÃO
                                     ) AS SITTRIBUTPF
                                   , 'P' AS TIPOCALCULOGNRE --P = NOTA ; C = EXTRA NOTA
                                   , 0 AS TV9ISENTOST
                                   , NVL( ICM.CUSCOMICMSBASEST, 'N' )
                                        AS USAVALORULTENTBASEST
                                   , NVL( ICM.CUSCOMICMSBASEST, 'N' )
                                        AS USAVALORULTENTBASEST2
                                   , 'N' AS USAVLULTENTMEDIOBASEST
                                   , 'N' AS UTILIZAPERCBASEREDPF
                                   , TPO.CODCFO_SAIDA
                                        AS CODFISCALVENDAPRONTAENT
                                   , TPO.CODCFO_SAIDA_FORA
                                        AS CODFISCALVENDAPRONTAENTINTER
                                   , CASE
                                        WHEN TPO.BONIFICACAO = 'S' THEN
                                           CODCFO_SAIDA
                                        ELSE
                                           0
                                     END
                                        AS CODFISCALBONIFIC
                                   , CASE
                                        WHEN TPO.BONIFICACAO = 'S' THEN
                                           CODCFO_SAIDA_FORA
                                        ELSE
                                           0
                                     END
                                        AS CODFISCALBONIFICINTER
                                   , 0 AS PRIORIDADE
                                   , OUTORGA AS PERDIFERIMENTOICMS
                                   , 0 AS CODGRUPOTRIBUT
                                FROM TGFICM ICM
                                   --, TGFPRI PRI
                                   , TGFTOP TPO
                                   , (SELECT *
                                        FROM TSIEMP E
                                       WHERE E.AD_MAXIMA = 'S') EMP
                                   , (SELECT --IPI
                                            NVL(
                                                 ( SELECT LOGICO
                                                    FROM TSIPAR
                                                   WHERE CHAVE =
                                                            'IPIINCICMS' )
                                               , 'N' )
                                                AS IPIINCICMS
                                        FROM DUAL) IPI
                               WHERE --ICM.TIPRESTRICAO = PRI.TIPRESTRICAO1
                                     --AND ICM.TIPRESTRICAO2 = PRI.TIPRESTRICAO2
                                     ICM.SEQUENCIA = 1
                                 AND ICM.TIPRESTRICAO = 'S'
                                 AND ICM.TIPRESTRICAO2 = 'S'
                                 AND TPO.DHALTER =
                                        ( SELECT MAX( DHALTER )
                                           FROM TGFTOP T2
                                          WHERE T2.CODTIPOPER =
                                                   TPO.CODTIPOPER )
                                 AND TPO.AD_MAXIMA_TIPOVENDA = V_TIPOVENDA
                                 AND TPO.TIPMOV =
                                        CASE
                                           WHEN V_TIPOVENDA = 14 THEN 'V'
                                           ELSE 'P'
                                        END
                                 AND TPO.DHALTER =
                                        ( SELECT MAX( DHALTER )
                                           FROM TGFTOP TPO2
                                          WHERE TPO2.CODTIPOPER =
                                                   TPO.CODTIPOPER )
                                 AND ICM.UFORIG =
                                        (SELECT UF
                                           FROM TSICID CID
                                          WHERE CID.CODCID = EMP.CODCID)) T) T) T;

   COMMIT;

   /* INSERINDO TRIBUTACAO PADRAO ( COM RESTRICAO ) */  
   INSERT INTO TRIBUTACAO_MAXIMA
   (   IDLINHA 
      , CODEMP 
      , CODPROD
      , CODFILIALNF
      , UFDESTINO 
      , CODOPER 
      , CODCLI 
      , AGREGARIPICALCULOST
      , ALIQICMS1 
      , ALIQICMS1FONTE
      , ALIQICMS2 
      , ALIQICMS2FONTE
      , CODICM 
      , CODICMPF
      , CODICMPRODRURAL
      , CODICMTAB 
      , CODICMTABPF
      , IVA 
      , IVAFONTE
      , MOSTRARPVENDASEMIPI
      , MOSTRARPVENDASEMST 
      , OBS
      , PAUTA
      , PERACRESCIMOPF 
      , PERBASEREDNRPA 
      , PERCACRESICMSPF_PI
      , PERCBASERED 
      , CONSUMIDOR 
      , TIPOSN 
      , PERCBASEREDST
      , PERCBASEREDSTFONTE
      , PERCBASESTRJ 
      , PERCDESCCOFINS
      , PERCDESCPIS 
      , PERDESCICMISENCAO
      , PERDESCPISSUFRAMA
      , PERDESCREPASSE 
      , PERDESCSUFRAMA
      , RIOLOGISENTOST 
      , SITTRIBUT 
      , SITTRIBUTPF
      , TIPOCALCULOGNRE
      , TV9ISENTOST 
      , USAVALORULTENTBASEST
      , USAVALORULTENTBASEST2
      , USAVLULTENTMEDIOBASEST
      , UTILIZAPERCBASEREDPF 
      , CODFISCALVENDAPRONTAENT
      , CODFISCALVENDAPRONTAENTINTER
      , CODFISCALBONIFIC 
      , CODFISCALBONIFICINTER
      , PRIORIDADE 
      , PERCBASEREDCONSUMIDOR
      , PERCREDPVENDASIMPLESNAC
      , PERDIFERIMENTOICMS 
      , CODGRUPOTRIBUT
      , ALIQICMSFECP
      , PERACRESCIMOFUNCEP
      )
      SELECT ROWNUM AS IDLINHA, T.*
        FROM (SELECT DISTINCT
                     CASE
                        WHEN NVL( CODEMP, 0 ) = 0 THEN
                           ( SELECT NVL( MIN( CODEMPBASE ), 1 )
                              FROM AD_MAXCONF )
                        ELSE
                           CODEMP
                     END
                        AS CODEMP
                   , NVL( CODPROD, 0 ) AS CODPROD
                   , CASE
                        WHEN NVL( CODFILIALNF, 0 ) = 0 THEN 1
                        ELSE CODFILIALNF
                     END
                        AS CODFILIALNF
                   , NVL( UFDESTINO, ' ' ) AS UFDESTINO
                   , NVL( CODOPER, 0 ) AS CODOPER
                   , NVL( CODCLI, 0 ) AS CODCLI
                   , NVL( AGREGARIPICALCULOST, 'N' ) AS AGREGARIPICALCULOST
                   , NVL( ALIQICMS1, 0 ) AS ALIQICMS1
                   , NVL( ALIQICMS1FONTE, 0 ) AS ALIQICMS1FONTE
                   , NVL( ALIQICMS2, 0 ) AS ALIQICMS2
                   , NVL( ALIQICMS2FONTE, 0 ) AS ALIQICMS2FONTE
                   , NVL( CODICM, 0 ) AS CODICM
                   , NVL( CODICMPF, 0 ) AS CODICMPF
                   , NVL( CODICMPRODRURAL, 0 ) AS CODICMPRODRURAL
                   , NVL( CODICMTAB, 0 ) AS CODICMTAB
                   , NVL( CODICMTABPF, 0 ) AS CODICMTABPF
                   , NVL( IVA, 0 ) AS IVA
                   , NVL( IVAFONTE, 0 ) AS IVAFONTE
                   , NVL( MOSTRARPVENDASEMIPI, 'N' ) AS MOSTRARPVENDASEMIPI
                   , NVL( MOSTRARPVENDASEMST, 'N' ) AS MOSTRARPVENDASEMST
                   , NVL( OBS, ' ' ) AS OBS
                   , NVL( PAUTA, 0 ) AS PAUTA
                   , NVL( PERACRESCIMOPF, 0 ) AS PERACRESCIMOPF
                   , NVL( PERBASEREDNRPA, 0 ) AS PERBASEREDNRPA
                   , NVL( PERCACRESICMSPF_PI, 0 ) AS PERCACRESICMSPF_PI
                   , NVL( PERCBASERED, 0 ) AS PERCBASERED
                   , NVL( CONSUMIDOR, 'N' ) AS CONSUMIDOR
                   , NVL( TIPOSN, 0 ) AS TIPOSN
                   , NVL( PERCBASEREDST, 0 ) AS PERCBASEREDST
                   , NVL( PERCBASEREDSTFONTE, 0 ) AS PERCBASEREDSTFONTE
                   , NVL( PERCBASESTRJ, 0 ) AS PERCBASESTRJ
                   , NVL( PERCDESCCOFINS, 0 ) AS PERCDESCCOFINS
                   , NVL( PERCDESCPIS, 0 ) AS PERCDESCPIS
                   , NVL( PERDESCICMISENCAO, 0 ) AS PERDESCICMISENCAO
                   , NVL( PERDESCPISSUFRAMA, 0 ) AS PERDESCPISSUFRAMA
                   , NVL( PERDESCREPASSE, 0 ) AS PERDESCREPASSE
                   , NVL( PERDESCSUFRAMA, 0 ) AS PERDESCSUFRAMA
                   , NVL( RIOLOGISENTOST, 0 ) AS RIOLOGISENTOST
                   , NVL( SITTRIBUT, 0 ) AS SITTRIBUT
                   , NVL( SITTRIBUTPF, SITTRIBUT ) AS SITTRIBUTPF
                   , NVL( TIPOCALCULOGNRE, 'P' ) AS TIPOCALCULOGNRE
                   , NVL( TV9ISENTOST, 0 ) AS TV9ISENTOST
                   , NVL( USAVALORULTENTBASEST, 'N' ) AS USAVALORULTENTBASEST
                   , NVL( USAVALORULTENTBASEST2, 'N' )
                        AS USAVALORULTENTBASEST2
                   , NVL( USAVLULTENTMEDIOBASEST, 'N' )
                        AS USAVLULTENTMEDIOBASEST
                   , NVL( UTILIZAPERCBASEREDPF, 0 ) AS UTILIZAPERCBASEREDPF
                   , NVL( CODFISCALVENDAPRONTAENT, 0 )
                        AS CODFISCALVENDAPRONTAENT
                   , NVL( CODFISCALVENDAPRONTAENTINTER, 0 )
                        AS CODFISCALVENDAPRONTAENTINTER
                   , NVL( CODFISCALBONIFIC, 0 ) AS CODFISCALBONIFIC
                   , NVL( CODFISCALBONIFICINTER, 0 ) AS CODFISCALBONIFICINTER
                   , NVL( PRIORIDADE, 0 ) AS PRIORIDADE
                   , NVL( PERCBASEREDCONSUMIDOR, 0 ) AS PERCBASEREDCONSUMIDOR
                   , NVL( PERCREDPVENDASIMPLESNAC, 0 ) AS PERCREDPVENDASIMPLESNAC
                   , NVL( PERDIFERIMENTOICMS, 0 ) AS PERDIFERIMENTOICMS     
                   , NVL( CODGRUPOTRIBUT, 0 ) AS CODGRUPOTRIBUT
                   , NVL( ALIQICMSFECP, 0 ) AS ALIQICMSFECP
                   , NVL( PERACRESCIMOFUNCEP, 0 ) AS PERACRESCIMOFUNCEP
                FROM (SELECT T.*
                           , CASE
                                WHEN T.CONSUMIDOR = 'S' THEN PERCBASERED
                                ELSE 0
                             END
                                AS PERCBASEREDCONSUMIDOR
                           -- % ICMS SIMPLES NACIONAL
                           , ( SELECT PSN.ALIQICMS
                                FROM TGFEMPSN EMPSN, TGFPSN PSN
                               WHERE EMPSN.CODEMP = T.CODEMP
                                 AND PSN.NUPARTILHA = EMPSN.NUPARTILHA
                                 AND ( ( T.TIPOSN = 1
                                    AND PSN.TIPOSN = 1 )
                                   OR ( T.TIPOSN = 2
                                   AND PSN.TIPOSN = 2 )
                                   OR ( T.TIPOSN = 3
                                   AND PSN.TIPOSN IN (3, 4) ) )
                                 AND EMPSN.DTREF =
                                        (SELECT MAX( E1.DTREF )
                                           FROM TGFEMPSN E1, TGFPSN P1
                                          WHERE E1.CODEMP = T.CODEMP
                                            AND P1.NUPARTILHA = E1.NUPARTILHA
                                            AND ( ( T.TIPOSN = 1
                                               AND P1.TIPOSN = 1 )
                                              OR ( T.TIPOSN = 2
                                              AND P1.TIPOSN = 2 )
                                              OR ( T.TIPOSN = 3
                                              AND P1.TIPOSN IN (3, 4) ) )
                                            AND E1.DTREF <= TRUNC( SYSDATE )) )
                                AS PERCREDPVENDASIMPLESNAC
                        FROM (SELECT EMP.CODEMP
                                   , PRO.CODPROD AS CODPROD
                                   , EMP.CODEMP AS CODFILIALNF
                                   , ( SELECT UF
                                        FROM TSIUFS
                                       WHERE CODUF = ICM.UFDEST )
                                        AS UFDESTINO
                                   , TPO.AD_MAXIMA_TIPOVENDA AS CODOPER
                                   , 0 AS CODCLI
                                   , IPI.IPIINCICMS AS AGREGARIPICALCULOST --Parametro IPIINCICMS
                                   , CASE
                                        WHEN ICM.UFORIG = ICM.UFDEST THEN
                                           NVL( ALIQSUBTRIB, 0 )
                                        ELSE
                                           0
                                     END
                                        AS ALIQICMS1 --Aliquota de ST Interno
                                   , CASE
                                        WHEN ICM.UFORIG = ICM.UFDEST THEN
                                           NVL( ALIQSUBTRIB, 0 )
                                        ELSE
                                           0
                                     END
                                        AS ALIQICMS1FONTE --Aliquota de ST Interno
                                   , CASE
                                        WHEN ICM.UFORIG <> ICM.UFDEST THEN
                                           NVL( ALIQSUBTRIB, 0 )
                                        ELSE
                                           0
                                     END
                                        AS ALIQICMS2 --Aliquota de ST Externo
                                   , CASE
                                        WHEN ICM.UFORIG <> ICM.UFDEST THEN
                                           NVL( ALIQSUBTRIB, 0 )
                                        ELSE
                                           0
                                     END
                                        AS ALIQICMS2FONTE --Aliquota de ST Externo
                                   , ICM.ALIQUOTA AS CODICM --Aliquota ICMS para PJ
                                   , ICM.ALIQUOTA AS CODICMPF --Aliquota ICMS para PF
                                   , 0 AS CODICMPRODRURAL
                                   --Aliquota ICMS para Produtor Rural
                                   , ICM.ALIQUOTA AS CODICMTAB --Aliquota ICMS para PJ
                                   , ICM.ALIQUOTA AS CODICMTABPF --Aliquota ICMS para PF
                                   , ICM.MARGLUCRO AS IVA
                                   , ICM.MARGLUCRO AS IVAFONTE
                                   , ICM.PERCSTFCPINT AS ALIQICMSFECP  --Fundo Combate a Pobreza ST
                                   , ICM.PERCICMSFCPINT AS PERACRESCIMOFUNCEP  --Fundo Combate a Pobreza ICMS INTERNO
                                   , 'N' AS MOSTRARPVENDASEMIPI
                                   , 'N' AS MOSTRARPVENDASEMST
                                   , '' AS OBS
                                   , CASE WHEN ICM.TIPRESTRICAO <> 'P' --EXCEÇÃO POR PRODUTO 
                                       THEN 0
                                       ELSE 
                                          NVL(( 
                                                SELECT E.VLRVENDA
                                                FROM TGFEXC E
                                                WHERE E.CODPROD = ICM.CODRESTRICAO
                                                AND E.NUTAB = (
                                                                  SELECT MAX(NUTAB) 
                                                                  FROM TGFTAB T 
                                                                  WHERE T.CODTAB = ICM.CODTAB
                                                                  AND EXISTS ( SELECT 1 FROM TGFEXC E WHERE T.NUTAB = E.NUTAB AND E.CODPROD = ICM.CODRESTRICAO )
                                                                  AND T.DTVIGOR = ( SELECT MAX(T.DTVIGOR) 
                                                                                     FROM TGFTAB T
                                                                                     WHERE T.CODTAB = ICM.CODTAB
                                                                                     AND T.DTVIGOR <= TRUNC(SYSDATE)
                                                                                     AND EXISTS ( SELECT 1 FROM TGFEXC E WHERE T.NUTAB = E.NUTAB AND E.CODPROD = ICM.CODRESTRICAO )
                                                                                    ) 
                                                                 )
                                             ),0)
                                       END AS PAUTA
                                   , 0 AS PERACRESCIMOPF
                                   , 0 AS PERBASEREDNRPA
                                   , 0 AS PERCACRESICMSPF_PI
                                   , ICM.REDBASE AS PERCBASERED
                                   , 'N' AS CONSUMIDOR
                                   , CASE
                                        WHEN ICM.CSOSN IN
                                                (101, 201, 102, 202) THEN
                                           CASE
                                              WHEN NVL( PRO.USOPROD, 'V' ) =
                                                      'V' THEN
                                                 2
                                              ELSE
                                                 1
                                           END
                                        ELSE
                                           0
                                     END
                                        AS TIPOSN
                                   , ICM.REDBASEST AS PERCBASEREDST
                                   , ICM.REDBASEST AS PERCBASEREDSTFONTE
                                   , 0 AS PERCBASESTRJ
                                   , 0 AS PERCDESCCOFINS
                                   , 0 AS PERCDESCPIS
                                   , 0 AS PERDESCICMISENCAO
                                   , 0 AS PERDESCPISSUFRAMA
                                   , REPPERCBASEICMS AS PERDESCREPASSE
                                   , REDBASEST AS PERDESCSUFRAMA
                                   , 0 AS RIOLOGISENTOST
                                   , ICM.CODTRIB AS SITTRIBUT
                                   , ( SELECT I.CODTRIB
                                        FROM TGFICM I
                                        WHERE I.UFORIG = ICM.UFORIG
                                          AND I.UFDEST = ICM.UFDEST
                                          AND I.TIPRESTRICAO2 = ICM.TIPRESTRICAO
                                          AND I.CODRESTRICAO2 = ICM.CODRESTRICAO
                                          AND I.TIPRESTRICAO = 'N'  --CONSUMIDOR
                                     ) AS SITTRIBUTPF
                                   , 'P' AS TIPOCALCULOGNRE --P = NOTA ; C = EXTRA NOTA
                                   , 0 AS TV9ISENTOST
                                   , NVL( ICM.CUSCOMICMSBASEST, 'N' )
                                        AS USAVALORULTENTBASEST
                                   , NVL( ICM.CUSCOMICMSBASEST, 'N' )
                                        AS USAVALORULTENTBASEST2
                                   , 'N' AS USAVLULTENTMEDIOBASEST
                                   , 'N' AS UTILIZAPERCBASEREDPF
                                   , TPO.CODCFO_SAIDA
                                        AS CODFISCALVENDAPRONTAENT
                                   , TPO.CODCFO_SAIDA_FORA
                                        AS CODFISCALVENDAPRONTAENTINTER
                                   , CASE
                                        WHEN TPO.BONIFICACAO = 'S' THEN
                                           TPO.CODCFO_SAIDA
                                        ELSE
                                           0
                                     END
                                        AS CODFISCALBONIFIC
                                   , CASE
                                        WHEN TPO.BONIFICACAO = 'S' THEN
                                           TPO.CODCFO_SAIDA_FORA
                                        ELSE
                                           0
                                     END
                                        AS CODFISCALBONIFICINTER
                                   , 0 AS PRIORIDADE
                                   , OUTORGA AS PERDIFERIMENTOICMS
                                   , CASE WHEN ICM.TIPRESTRICAO = 'I' THEN ICM.CODRESTRICAO ELSE 0 END AS CODGRUPOTRIBUT
                                FROM (SELECT ICM.*
                                        FROM TGFICM ICM
                                        WHERE ICM.TIPRESTRICAO = 'P' --EXCEÇÃO POR PRODUTO 
                                        AND ICM.TIPRESTRICAO2 = 'S' --SEM EXCEÇÃO
                                        AND EXISTS ( SELECT 1 FROM TGFPRO PRO WHERE PRO.CODPROD = ICM.CODRESTRICAO
                                                                                AND PRO.USOPROD IN ('R', 'V')
                                                                                AND PRO.CODPROD <> 0
                                                                                AND PRO.ATIVO = 'S'
                                                                                AND PRO.AD_MAXIMA = 'S' )
                                      UNION
                                      SELECT ICM.*
                                        FROM TGFICM ICM
                                        WHERE ICM.TIPRESTRICAO = 'I' --EXCEÇÃO POR GRUPO DE ICMS DO PRODUTO 
                                        AND ICM.TIPRESTRICAO2 = 'S' --SEM EXCEÇÃO
                                        AND EXISTS ( SELECT 1 FROM TGFPRO PRO WHERE PRO.GRUPOICMS = ICM.CODRESTRICAO
                                                                                AND PRO.USOPROD IN ('R', 'V')
                                                                                AND PRO.CODPROD <> 0
                                                                                AND PRO.ATIVO = 'S'
                                                                                AND PRO.AD_MAXIMA = 'S' )


                                               ) ICM
                                     LEFT JOIN TGFPRO PRO
                                        ON ICM.TIPRESTRICAO = 'P'
                                       AND ICM.CODRESTRICAO = PRO.CODPROD
                                   , TGFTOP TPO
                                   , (SELECT *
                                        FROM TSIEMP E
                                       WHERE E.AD_MAXIMA = 'S') EMP
                                   , (SELECT --IPI
                                            NVL(
                                                 ( SELECT LOGICO
                                                    FROM TSIPAR
                                                   WHERE CHAVE =
                                                            'IPIINCICMS' )
                                               , 'N' )
                                                AS IPIINCICMS
                                        FROM DUAL) IPI
                               WHERE TPO.AD_MAXIMA_TIPOVENDA = V_TIPOVENDA
                                 AND TPO.TIPMOV =
                                        CASE
                                           WHEN V_TIPOVENDA = 14 THEN 'V'
                                           ELSE 'P'
                                        END
                                 AND TPO.DHALTER =
                                        ( SELECT MAX( DHALTER )
                                           FROM TGFTOP TPO2
                                          WHERE TPO2.CODTIPOPER =
                                                   TPO.CODTIPOPER )
                                 AND ICM.UFORIG =
                                        (SELECT UF
                                           FROM TSICID CID
                                          WHERE CID.CODCID = EMP.CODCID)) T) T) T;

   COMMIT;
END;
/

/*
NomeObjeto: STP_GERALOG_BD
TipoObjeto: PROCEDURE
NomeTabela: STP_GERALOG_BD
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_GERALOG_BD( V_TIPO_REGISTRO   IN VARCHAR2
                                          , V_OPERACAO        IN VARCHAR2
                                          , V_CHAVE           IN VARCHAR2
                                          , V_MENSAGEM        IN VARCHAR2
                                          , V_REQUEST         IN VARCHAR2
                                          , V_RESPONSE        IN CLOB
                                          , V_BODY            IN CLOB
                                          , V_TIPO_LOG        IN INT
                                          , V_STACKTRACE      IN CLOB ) AS
   PRAGMA AUTONOMOUS_TRANSACTION;
   V_MENORDATALOG DATE;
BEGIN
   --BUSCANDO MENOR DATA NO LOG
   SELECT TRUNC(NVL( MIN(DH_LOG), SYSDATE)) INTO V_MENORDATALOG 
   FROM AD_MAXIMALOG;
   
   --MANTÉM NO LOG APENAS LINHAS COM ATÉ 15 DIAS
   IF V_MENORDATALOG < TRUNC(SYSDATE) - 15 THEN
     DELETE FROM AD_MAXIMALOG WHERE TRUNC(DH_LOG) < TRUNC(SYSDATE) - 15;
   END IF;

   INSERT INTO AD_MAXIMALOG( ID
                           , TIPO_REGISTRO
                           , OPERACAO
                           , CHAVE
                           , DH_LOG
                           , MENSAGEM
                           , REQUEST
                           , RESPONSE
                           , BODY
                           , TIPO_LOG
                           , STACKTRACE )
   VALUES ( SEQUENCE_LOG_MAXIMA.NEXTVAL
          , V_TIPO_REGISTRO
          , V_OPERACAO
          , V_CHAVE
          , SYSDATE
          , V_MENSAGEM
          , V_REQUEST
          , V_RESPONSE
          , V_BODY
          , V_TIPO_LOG
          , V_STACKTRACE );

   COMMIT;
END;
/

/*
NomeObjeto: STP_SALVAERRO_BD
TipoObjeto: PROCEDURE
NomeTabela: STP_SALVAERRO_BD
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_SALVAERRO_BD(
   P_NUFIN         IN NUMBER
 , P_CODVEND       IN NUMBER
 , P_TIPO          IN CHAR
 , P_CAIXAMX       IN VARCHAR2
 , P_MOVIMENTOMX   IN VARCHAR2
 , P_MENSAGEM      IN VARCHAR2
 , P_CODERRO       IN NUMBER
 , P_JSONREQUEST   IN VARCHAR2 ) AS
   PRAGMA AUTONOMOUS_TRANSACTION;
   V_MENORDATALOG DATE;
BEGIN
       
      --BUSCANDO MENOR DATA NO LOG
      SELECT TRUNC( NVL( MIN(DHLOG), SYSDATE ) ) INTO V_MENORDATALOG
      FROM TEIPCV_MAXIMA;
   
      --MANTÉM NO LOG APENAS LINHAS COM ATÉ 15 DIAS
      IF V_MENORDATALOG < TRUNC(SYSDATE) - 15 THEN
       --EXCLUINDO LINHAS ANTIGAS 
        DELETE FROM TEIPCV_MAXIMA 
        WHERE DHLOG IS NULL OR TRUNC(DHLOG) < TRUNC(SYSDATE - 15); 
      END IF;       

   INSERT INTO TEIPCV_MAXIMA( ID
                            , NUFIN
                            , CODVEND
                            , TIPO
                            , CAIXAMX
                            , MOVIMENTOMX
                            , MENSAGEM
                            , CODERRO
                            , JSONREQUEST
                            , DHLOG )
   VALUES ( SEQUENCE_ERRO_MAXIMA.NEXTVAL
          , P_NUFIN
          , P_CODVEND
          , P_TIPO
          , P_CAIXAMX
          , P_MOVIMENTOMX
          , P_MENSAGEM
          , P_CODERRO
          , P_JSONREQUEST
          , SYSDATE );

   COMMIT;
END;
/

/*
NomeObjeto: STP_MAX_OBTEM_TRIB
TipoObjeto: PROCEDURE
NomeTabela: STP_MAX_OBTEM_TRIB
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_MAX_OBTEM_TRIB(
   P_CODUFORIG          IN     NUMBER
 , P_CODUFDEST          IN     NUMBER
 , P_CODPROD            IN     NUMBER
 , P_CODGRUPOPROD       IN     NUMBER
 , P_GIPROD             IN     NUMBER
 , P_GIPROD2            IN     NUMBER
 , P_CODEMP             IN     NUMBER
 , P_GIGRUPOPROD        IN     NUMBER
 , V_ALIQSUBTRIB           OUT FLOAT
 , V_ALIQUOTA              OUT FLOAT
 , V_CODTRIB               OUT NUMBER
 , V_CUSCOMICMSBASEST      OUT CHAR
 , V_MARGLUCRO             OUT FLOAT
 , V_REDBASE               OUT FLOAT
 , V_REDBASEST             OUT FLOAT
 , V_REPPERCBASEICMS       OUT FLOAT
 , V_PRIORIDADE            OUT NUMBER ) AS
   ERRMSG   VARCHAR2( 4000 );
   ERROR    EXCEPTION;
BEGIN
   SELECT T.ALIQSUBTRIB
        , T.ALIQUOTA
        , T.CODTRIB
        , T.CUSCOMICMSBASEST
        , T.MARGLUCRO
        , T.REDBASE
        , T.REDBASEST
        , T.REPPERCBASEICMS
        , T.PRIORIDADE
     INTO V_ALIQSUBTRIB
        , V_ALIQUOTA
        , V_CODTRIB
        , V_CUSCOMICMSBASEST
        , V_MARGLUCRO
        , V_REDBASE
        , V_REDBASEST
        , V_REPPERCBASEICMS
        , V_PRIORIDADE
     FROM (SELECT I.ALIQSUBTRIB
                , I.ALIQUOTA
                , I.CODTRIB
                , I.CUSCOMICMSBASEST
                , I.MARGLUCRO
                , I.REDBASE
                , I.REDBASEST
                , I.REPPERCBASEICMS
                , P.PRIORIDADE
             FROM TGFICM I, TGFPRI P
            WHERE I.UFORIG = P_CODUFORIG
              AND I.UFDEST = P_CODUFDEST
              AND I.TIPRESTRICAO = P.TIPRESTRICAO1
              AND I.TIPRESTRICAO2 = P.TIPRESTRICAO2
              AND ( ( I.TIPRESTRICAO = 'S' )
                OR ( I.TIPRESTRICAO = 'P'
                AND I.CODRESTRICAO = P_CODPROD )
                OR ( I.TIPRESTRICAO = 'G'
                AND I.CODRESTRICAO = P_CODGRUPOPROD )
                OR ( I.TIPRESTRICAO = 'I'
                AND I.CODRESTRICAO = P_GIPROD )
                OR ( I.TIPRESTRICAO = 'K'
                AND I.CODRESTRICAO = P_GIPROD2 )
                OR ( I.TIPRESTRICAO = 'M'
                AND I.CODRESTRICAO = P_CODEMP )
                OR ( I.TIPRESTRICAO = 'J'
                AND I.CODRESTRICAO = P_GIGRUPOPROD ) )
              AND ( ( I.TIPRESTRICAO2 = 'S' )
                OR ( I.TIPRESTRICAO2 = 'P'
                AND I.CODRESTRICAO2 = P_CODPROD )
                OR ( I.TIPRESTRICAO2 = 'G'
                AND I.CODRESTRICAO2 = P_CODGRUPOPROD )
                OR ( I.TIPRESTRICAO2 = 'I'
                AND I.CODRESTRICAO2 = P_GIPROD )
                OR ( I.TIPRESTRICAO2 = 'K'
                AND I.CODRESTRICAO2 = P_GIPROD2 )
                OR ( I.TIPRESTRICAO2 = 'M'
                AND I.CODRESTRICAO2 = P_CODEMP )
                OR ( I.TIPRESTRICAO2 = 'J'
                AND I.CODRESTRICAO2 = P_GIGRUPOPROD ) )
           ORDER BY P.PRIORIDADE) T
    WHERE ROWNUM = 1;
EXCEPTION
   WHEN OTHERS THEN
      ERRMSG :=
         'ERRO AO OBTER TRIBUTACAO.' || CHR( 13 ) ||
         'AS CONFIGURACOES DE TRIBUTACAO ESTAO INCORRETAS PARA OS SEGUINTES DADOS:'
         || CHR( 13 ) || 'PRODUTO - :' || P_CODPROD || CHR( 13 ) ||
         'UF ORIGEM - ' || P_CODUFORIG || CHR( 13 ) || 'UF ORIDESTINO - ' ||
         P_CODUFDEST || CHR( 13 ) || SUBSTR( SQLERRM, 1, 500 );
      RAISE_APPLICATION_ERROR( -20101, ERRMSG );
END;
/

/*
NomeObjeto: STP_TRIBUTACAO_MAXIMAUF
TipoObjeto: PROCEDURE
NomeTabela: STP_TRIBUTACAO_MAXIMAUF
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_TRIBUTACAO_MAXIMAUF AS
   ERRMSG   VARCHAR( 100 );
BEGIN
   /* LIMPANDO A TABELA DE TRIBUTACOO MAXIMA */
   EXECUTE IMMEDIATE 'TRUNCATE TABLE TRIBUTACAO_MAXIMA';

   BEGIN
      MERGE INTO TRIBUTACAO_MAXIMA TM
       USING (WITH TRIBUTOS AS
                      (SELECT 0 AS IDLINHA
                            , T.ALIQSUBTRIB AS ALIQSUBTRIB
                            , T.ALIQUOTA AS ALIQUOTA
                            , T.CODTRIB AS CODTRIB
                            , T.CUSCOMICMSBASEST AS CUSCOMICMSBASEST
                            , T.MARGLUCRO AS MARGLUCRO
                            , T.REDBASE AS REDBASE
                            , T.REDBASEST AS REDBASEST
                            , T.REPPERCBASEICMS AS REPPERCBASEICMS
                            , T.CODFILIALNF AS CODEMP
                            , T.CODFILIALNF AS CODFILIALNF
                            , T.CODUFORIG AS CODUFORIG
                            , T.CODUFDESTINO AS CODUFDESTINO
                            , T.UFDESTINO AS UFDESTINO
                            , CASE WHEN T.CODGRUPOTRIBUT <> 0 THEN T.CODPROD ELSE 0 END AS CODPROD
                            , CODGRUPOTRIBUT AS CODGRUPOTRIBUT
                            , T.CODUF AS CODUF
                            , T.CODGRUPOPROD AS CODGRUPOPROD
                            , T.GRUPOICMS AS GRUPOICMS
                            , T.GRUPOICMS2 AS GRUPOICMS2
                            , T.GIGRUPOPROD AS GIGRUPOPROD
                            , T.PERDIFERIMENTOICMS AS PERDIFERIMENTOICMS
                            , 1 AS CODOPER
                            , 0 AS CODCLI
                            , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS1 --Aliquota de ST Interno
                            , NVL( ALIQSUBTRIB, 0 ) AS ALIQICMS1FONTE --Aliquota de ST Interno
                            , NVL( ALIQUOTA, 0 ) AS ALIQICMS2 --Aliquota de ST Externo
                            , NVL( ALIQUOTA, 0 ) AS ALIQICMS2FONTE --Aliquota de ST Externo
                            , NVL( PERCSTFCPINT , 0 ) AS ALIQICMSFECP  --Fundo Combate a Pobreza ST
                            , NVL( PERCICMSFCPINT , 0 ) AS PERACRESCIMOFUNCEP  --Fundo Combate a Pobreza ICMS INTERNO
                            , NVL( ALIQUOTA, 0 ) AS CODICM
                            , NVL( ALIQUOTA, 0 ) AS CODICMPF
                            , NVL( ALIQUOTA, 0 ) AS CODICMPRODRURAL
                            , NVL( ALIQUOTA, 0 ) AS CODICMTAB
                            , NVL( ALIQUOTA, 0 ) AS CODICMTABPF
                            , NVL( MARGLUCRO, 0 ) AS IVA
                            , NVL( MARGLUCRO, 0 ) AS IVAFONTE
                            , 'N' AS MOSTRARPVENDASEMIPI
                            , 'N' AS MOSTRARPVENDASEMST
                            , '' AS OBS
                            , T.PAUTA AS PAUTA
                            , 0 AS PERACRESCIMOPF
                            , 0 AS PERBASEREDNRPA
                            , 0 AS PERCACRESICMSPF_PI
                            , NVL( ( SELECT LOGICO
                                      FROM TSIPAR
                                     WHERE CHAVE = 'IPIINCICMS' )
                                 , 'N' )
                                 AS AGREGARIPICALCULOST
                            , CASE
                                 WHEN REDBASEST IS NULL THEN 0
                                 ELSE 100 - REDBASEST
                              END
                                 AS PERCBASERED
                            , 'N' AS CONSUMIDOR
                            , 0 AS TIPOSN
                            , 0 AS PERCBASEREDST
                            , 0 AS PERCBASEREDSTFONTE
                            , 0 AS PERCBASESTRJ
                            , 0 AS PERCDESCCOFINS
                            , 0 AS PERCDESCPIS
                            , 0 AS PERDESCICMISENCAO
                            , 0 AS PERDESCPISSUFRAMA
                            , NVL( REPPERCBASEICMS, 0 ) AS PERDESCREPASSE
                            , 0 AS PERDESCSUFRAMA
                            , 0 AS RIOLOGISENTOST
                            , SITTRIBUT
                            , NVL( SITTRIBUTPF, SITTRIBUT ) AS SITTRIBUTPF
                            , 'P' AS TIPOCALCULOGNRE
                            , 0 AS TV9ISENTOST
                            , NVL( CUSCOMICMSBASEST, 'N' )
                                 AS USAVALORULTENTBASEST
                            , NVL( CUSCOMICMSBASEST, 'N' )
                                 AS USAVALORULTENTBASEST2
                            , 'N' AS USAVLULTENTMEDIOBASEST
                            , 'N' AS UTILIZAPERCBASEREDPF
                            , 0 AS CODFISCALVENDAPRONTAENT
                            , 0 AS CODFISCALVENDAPRONTAENTINTER
                            , 0 AS CODFISCALBONIFIC
                            , 0 AS CODFISCALBONIFICINTER
                            , PRIORIDADE
                            , 0 AS PERCBASEREDCONSUMIDOR
                            , 0 AS PERCREDPVENDASIMPLESNAC
                         FROM (SELECT I.ALIQSUBTRIB
                                    , I.ALIQUOTA
                                    , I.CODTRIB
                                    , I.CUSCOMICMSBASEST
                                    , I.MARGLUCRO
                                    , I.REDBASE
                                    , I.REDBASEST
                                    , I.REPPERCBASEICMS
                                    , I.PERCSTFCPINT
                                    , I.PERCICMSFCPINT
                                    , I.OUTORGA AS PERDIFERIMENTOICMS
                                    , NVL( I.CODTRIB, 0 ) AS SITTRIBUT
                                    , ( SELECT I2.CODTRIB
                                         FROM TGFICM I2
                                        WHERE I2.UFORIG = I.UFORIG
                                          AND I2.UFDEST = I.UFDEST
                                          AND I2.TIPRESTRICAO2 =
                                                 I.TIPRESTRICAO
                                          AND I2.CODRESTRICAO2 =
                                                 I.CODRESTRICAO
                                          AND I2.TIPRESTRICAO = 'N' --CONSUMIDOR
                                                                    )
                                         AS SITTRIBUTPF
                                    , P.PRIORIDADE
                                    , PRO.CODFILIALNF
                                    , PRO.CODUFORIG
                                    , PRO.CODUFDESTINO
                                    , PRO.UFDESTINO
                                    , PRO.CODPROD
                                    , PRO.CODCLI
                                    , PRO.CODOPER
                                    , PRO.CODUF
                                    , PRO.CODGRUPOPROD
                                    , PRO.GRUPOICMS
                                    , PRO.GRUPOICMS2
                                    , PRO.GIGRUPOPROD
                                    , CASE
                                         WHEN I.TIPRESTRICAO = 'I' THEN
                                            I.CODRESTRICAO
                                         ELSE
                                            0
                                      END
                                         AS CODGRUPOTRIBUT
                                    , CASE WHEN I.TIPRESTRICAO <> 'P' --EXCEÇÃO POR PRODUTO 
                                       THEN 0
                                       ELSE 
                                          NVL(( 
                                                SELECT E.VLRVENDA
                                                FROM TGFEXC E
                                                WHERE E.CODPROD = I.CODRESTRICAO
                                                AND E.NUTAB = (
                                                                  SELECT MAX(NUTAB) 
                                                                  FROM TGFTAB T 
                                                                  WHERE T.CODTAB = I.CODTAB
                                                                  AND EXISTS ( SELECT 1 FROM TGFEXC E WHERE T.NUTAB = E.NUTAB AND E.CODPROD = I.CODRESTRICAO )
                                                                  AND T.DTVIGOR = ( SELECT MAX(T.DTVIGOR) 
                                                                                     FROM TGFTAB T
                                                                                     WHERE T.CODTAB = I.CODTAB
                                                                                     AND T.DTVIGOR <= TRUNC(SYSDATE)
                                                                                     AND EXISTS ( SELECT 1 FROM TGFEXC E WHERE T.NUTAB = E.NUTAB AND E.CODPROD = I.CODRESTRICAO )
                                                                                    ) 
                                                                 )
                                             ),0)
                                       END AS PAUTA     
                                 FROM TGFICM I
                                    , TGFPRI P
                                    , (SELECT E.CODEMP CODFILIALNF
                                            , E.CODEMP
                                            , ( SELECT C.UF
                                                 FROM TSICID C
                                                WHERE C.CODCID = E.CODCID )
                                                 AS CODUFORIG
                                            , U.CODUF CODUFDESTINO
                                            , U.UF UFDESTINO
                                            , P.CODPROD
                                            , 0 CODCLI
                                            , 1 CODOPER
                                            , U.CODUF
                                            , P.CODGRUPOPROD
                                            , P.GRUPOICMS
                                            , P.GRUPOICMS2
                                            , ( SELECT G.GRUPOICMS
                                                 FROM TGFGRU G
                                                WHERE G.CODGRUPOPROD =
                                                         P.CODGRUPOPROD )
                                                 AS GIGRUPOPROD
                                         FROM TSIEMP E, TSIUFS U, TGFPRO P
                                        WHERE E.AD_MAXIMA = 'S'
                                          AND U.UF > '0'
                                          AND P.AD_MAXIMA = 'S') PRO
                                WHERE I.UFORIG = PRO.CODUFORIG
                                  AND I.UFDEST = PRO.CODUFDESTINO
                                  AND I.TIPRESTRICAO = P.TIPRESTRICAO1
                                  AND I.TIPRESTRICAO2 = P.TIPRESTRICAO2
                                  AND P.PRIORIDADE =
                                         ( SELECT MIN( PRIORIDADE )
                                            FROM TGFPRI PRI
                                           WHERE PRI.TIPRESTRICAO1 =
                                                    P.TIPRESTRICAO1
                                             AND PRI.TIPRESTRICAO2 =
                                                    P.TIPRESTRICAO2 )
                                  AND ( ( I.TIPRESTRICAO = 'S' )
                                    OR ( I.TIPRESTRICAO = 'P'
                                    AND I.CODRESTRICAO = PRO.CODPROD )
                                    OR ( I.TIPRESTRICAO = 'G'
                                    AND I.CODRESTRICAO = PRO.CODGRUPOPROD )
                                    OR ( I.TIPRESTRICAO = 'I'
                                    AND I.CODRESTRICAO = PRO.GRUPOICMS )
                                    OR ( I.TIPRESTRICAO = 'K'
                                    AND I.CODRESTRICAO = PRO.GRUPOICMS2 )
                                    OR ( I.TIPRESTRICAO = 'M'
                                    AND I.CODRESTRICAO = PRO.CODEMP )
                                    OR ( I.TIPRESTRICAO = 'J'
                                    AND I.CODRESTRICAO = PRO.GIGRUPOPROD ) )
                                  AND ( ( I.TIPRESTRICAO2 = 'S' )
                                    OR ( I.TIPRESTRICAO2 = 'P'
                                    AND I.CODRESTRICAO2 = PRO.CODPROD )
                                    OR ( I.TIPRESTRICAO2 = 'G'
                                    AND I.CODRESTRICAO2 = PRO.CODGRUPOPROD )
                                    OR ( I.TIPRESTRICAO2 = 'I'
                                    AND I.CODRESTRICAO2 = PRO.GRUPOICMS )
                                    OR ( I.TIPRESTRICAO2 = 'K'
                                    AND I.CODRESTRICAO2 = PRO.GRUPOICMS2 )
                                    OR ( I.TIPRESTRICAO2 = 'M'
                                    AND I.CODRESTRICAO2 = PRO.CODEMP )
                                    OR ( I.TIPRESTRICAO2 = 'J'
                                    AND I.CODRESTRICAO2 = PRO.GIGRUPOPROD ) )) T)
              SELECT T.*
                FROM TRIBUTOS T
               WHERE T.PRIORIDADE =
                        (SELECT MIN( PRIORIDADE )
                           FROM TRIBUTOS T2
                          WHERE T2.CODUFORIG = T.CODUFORIG
                            AND T2.CODUFDESTINO = T.CODUFDESTINO
                            AND T2.CODPROD = T.CODPROD
                            AND T2.CODGRUPOTRIBUT = T.CODGRUPOTRIBUT
                            AND T2.CODEMP = T.CODEMP)) TRIB_UF
          ON ( TM.CODPROD = TRIB_UF.CODPROD
          AND TM.CODFILIALNF = TRIB_UF.CODEMP
          AND TM.UFDESTINO = TRIB_UF.UFDESTINO )
      WHEN NOT MATCHED THEN
         INSERT ( IDLINHA
                , CODEMP
                , CODPROD
                , CODFILIALNF
                , UFDESTINO
                , CODOPER
                , CODCLI
                , AGREGARIPICALCULOST
                , ALIQICMS1
                , ALIQICMS1FONTE
                , ALIQICMS2
                , ALIQICMS2FONTE
                , CODICM
                , CODICMPF
                , CODICMPRODRURAL
                , CODICMTAB
                , CODICMTABPF
                , IVA
                , IVAFONTE
                , MOSTRARPVENDASEMIPI
                , MOSTRARPVENDASEMST
                , OBS
                , PAUTA
                , PERACRESCIMOPF
                , PERBASEREDNRPA
                , PERCACRESICMSPF_PI
                , PERCBASERED
                , CONSUMIDOR
                , TIPOSN
                , PERCBASEREDST
                , PERCBASEREDSTFONTE
                , PERCBASESTRJ
                , PERCDESCCOFINS
                , PERCDESCPIS
                , PERDESCICMISENCAO
                , PERDESCPISSUFRAMA
                , PERDESCREPASSE
                , PERDESCSUFRAMA
                , RIOLOGISENTOST
                , SITTRIBUT
                , SITTRIBUTPF
                , TIPOCALCULOGNRE
                , TV9ISENTOST
                , USAVALORULTENTBASEST
                , USAVALORULTENTBASEST2
                , USAVLULTENTMEDIOBASEST
                , UTILIZAPERCBASEREDPF
                , CODFISCALVENDAPRONTAENT
                , CODFISCALVENDAPRONTAENTINTER
                , CODFISCALBONIFIC
                , CODFISCALBONIFICINTER
                , PRIORIDADE
                , PERCBASEREDCONSUMIDOR
                , PERCREDPVENDASIMPLESNAC
                , PERDIFERIMENTOICMS
                , CODGRUPOTRIBUT
                , ALIQICMSFECP
                , PERACRESCIMOFUNCEP )
         VALUES ( TRIB_UF.IDLINHA
                , TRIB_UF.CODEMP
                , TRIB_UF.CODPROD
                , TRIB_UF.CODFILIALNF
                , TRIB_UF.UFDESTINO
                , TRIB_UF.CODOPER
                , TRIB_UF.CODCLI
                , TRIB_UF.AGREGARIPICALCULOST
                , TRIB_UF.ALIQICMS1
                , TRIB_UF.ALIQICMS1FONTE
                , TRIB_UF.ALIQICMS2
                , TRIB_UF.ALIQICMS2FONTE
                , TRIB_UF.CODICM
                , TRIB_UF.CODICMPF
                , TRIB_UF.CODICMPRODRURAL
                , TRIB_UF.CODICMTAB
                , TRIB_UF.CODICMTABPF
                , TRIB_UF.IVA
                , TRIB_UF.IVAFONTE
                , TRIB_UF.MOSTRARPVENDASEMIPI
                , TRIB_UF.MOSTRARPVENDASEMST
                , TRIB_UF.OBS
                , TRIB_UF.PAUTA
                , TRIB_UF.PERACRESCIMOPF
                , TRIB_UF.PERBASEREDNRPA
                , TRIB_UF.PERCACRESICMSPF_PI
                , TRIB_UF.PERCBASERED
                , TRIB_UF.CONSUMIDOR
                , TRIB_UF.TIPOSN
                , TRIB_UF.PERCBASEREDST
                , TRIB_UF.PERCBASEREDSTFONTE
                , TRIB_UF.PERCBASESTRJ
                , TRIB_UF.PERCDESCCOFINS
                , TRIB_UF.PERCDESCPIS
                , TRIB_UF.PERDESCICMISENCAO
                , TRIB_UF.PERDESCPISSUFRAMA
                , TRIB_UF.PERDESCREPASSE
                , TRIB_UF.PERDESCSUFRAMA
                , TRIB_UF.RIOLOGISENTOST
                , TRIB_UF.SITTRIBUT
                , TRIB_UF.SITTRIBUTPF
                , TRIB_UF.TIPOCALCULOGNRE
                , TRIB_UF.TV9ISENTOST
                , TRIB_UF.USAVALORULTENTBASEST
                , TRIB_UF.USAVALORULTENTBASEST2
                , TRIB_UF.USAVLULTENTMEDIOBASEST
                , TRIB_UF.UTILIZAPERCBASEREDPF
                , TRIB_UF.CODFISCALVENDAPRONTAENT
                , TRIB_UF.CODFISCALVENDAPRONTAENTINTER
                , TRIB_UF.CODFISCALBONIFIC
                , TRIB_UF.CODFISCALBONIFICINTER
                , TRIB_UF.PRIORIDADE
                , TRIB_UF.PERCBASEREDCONSUMIDOR
                , TRIB_UF.PERCREDPVENDASIMPLESNAC
                , TRIB_UF.PERDIFERIMENTOICMS
                , TRIB_UF.CODGRUPOTRIBUT
                , TRIB_UF.ALIQICMSFECP
                , TRIB_UF.PERACRESCIMOFUNCEP );

      COMMIT;
   EXCEPTION
      WHEN OTHERS THEN
         ROLLBACK;
         ERRMSG :=
            'FALHA AO PREPARAR TRIBUTACAO PARA SER ENVIADA A MAXIMA.' || CHR
            ( 13 ) || SUBSTR( SQLERRM, 1, 500 );
         RAISE_APPLICATION_ERROR( -20111, ERRMSG );
   END;
END;
/

/*
NomeObjeto: STP_GRAVA_CAIXA_MAX
TipoObjeto: PROCEDURE
NomeTabela: STP_GRAVA_CAIXA_MAX
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_GRAVA_CAIXA_MAX(
   P_ACAO                 IN INT
 , P_DHACAO               IN DATE
 , P_CODPRESTACAOCONTAC   IN VARCHAR2
 , P_DATAABERTURA         IN DATE
 , P_DATAFECHAMENTO       IN DATE
 , P_CODUSUR              IN NUMBER
 , P_NUMCARMANIF          IN VARCHAR
 , P_NUMLACRE             IN NUMBER
 , P_TOTALDESPESAS        IN NUMBER
 , P_TOTALRECEBIMENTOS    IN NUMBER
 , P_TOTALDEPOSITOS       IN NUMBER
 , P_NUCAIXA              IN NUMBER
 , P_DTFECHAMENTO         IN DATE
 , P_DTABERTURA           IN DATE ) AS
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   MERGE INTO AD_CAIXA_MAX
    USING DUAL
       ON ( CODPRESTACAOCONTAC = P_CODPRESTACAOCONTAC
       AND DATAFECHAMENTO IS NULL
       AND DTFECHAMENTO IS NULL )
   WHEN MATCHED THEN
      UPDATE SET ACAO = P_ACAO
               , DHACAO = P_DHACAO
               , DATAABERTURA = P_DATAABERTURA
               , CODUSUR = P_CODUSUR
               , NUMCARMANIF = P_NUMCARMANIF
               , NUMLACRE = P_NUMLACRE
               , TOTALDESPESAS = P_TOTALDESPESAS
               , TOTALRECEBIMENTOS = P_TOTALRECEBIMENTOS
               , TOTALDEPOSITOS = P_TOTALDEPOSITOS
               , NUCAIXA = P_NUCAIXA
               , DTABERTURA = P_DTABERTURA
   WHEN NOT MATCHED THEN
      INSERT ( ACAO
             , DHACAO
             , CODPRESTACAOCONTAC
             , DATAABERTURA
             , DATAFECHAMENTO
             , CODUSUR
             , NUMCARMANIF
             , NUMLACRE
             , TOTALDESPESAS
             , TOTALRECEBIMENTOS
             , TOTALDEPOSITOS
             , NUCAIXA
             , DTFECHAMENTO
             , DTABERTURA )
      VALUES ( P_ACAO
             , P_DHACAO
             , P_CODPRESTACAOCONTAC
             , P_DATAABERTURA
             , P_DATAFECHAMENTO
             , P_CODUSUR
             , P_NUMCARMANIF
             , P_NUMLACRE
             , P_TOTALDESPESAS
             , P_TOTALRECEBIMENTOS
             , P_TOTALDEPOSITOS
             , P_NUCAIXA
             , P_DTFECHAMENTO
             , P_DTABERTURA );

   COMMIT;
END;
/

/*
NomeObjeto: STP_GRAVA_MOV_CAIXA_MAX
TipoObjeto: PROCEDURE
NomeTabela: STP_GRAVA_MOV_CAIXA_MAX
Executar  : SEMPRE
*/ 

CREATE OR REPLACE PROCEDURE STP_GRAVA_MOV_CAIXA_MAX(
   P_ACAO                 IN INT
 , P_DHACAO               IN DATE
 , P_CODPRESTACAOCONTAC   IN VARCHAR
 , P_ID_CAIXA_MAX         IN NUMBER
 , P_CODPRESTACAOCONTAI   IN VARCHAR
 , P_DATALANCAMENTO       IN DATE
 , P_NUMTRANSVENDA        IN NUMBER
 , P_TIPO                 IN INT
 , P_VALOR                IN NUMBER
 , P_VLJUROS              IN NUMBER
 , P_VLDESCONTO           IN NUMBER
 , P_NUMPEDRCA            IN NUMBER
 , P_EXCLUIDO             IN CHAR
 , P_ID_ERP               IN NUMBER
 , P_FORMAPAGAMENTO       IN INT
 , P_NUFIN                IN NUMBER
 , P_NUBCO                IN NUMBER
 , P_DTNEG                IN DATE
 , P_DTVENC               IN DATE
 , P_DHMOV                IN DATE
 , P_DTALTER              IN DATE
 , P_RECDESP              IN INT
 , P_CODCTABCOINT         IN INT
 , P_CODTIPTIT            IN INT
 , P_DESDOBRAMENTO        IN NUMBER
 , P_VLRDESDOB            IN NUMBER
 , P_VLRDESC              IN NUMBER
 , P_VLRJUROS             IN NUMBER
 , P_VLRLANCSNK           IN NUMBER
 , P_SALDOSNK             IN NUMBER
 , P_CODLANC              IN NUMBER ) AS
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   MERGE INTO AD_MOVIMENTOCX_MAX
    USING DUAL
       ON ( CODPRESTACAOCONTAI = P_CODPRESTACAOCONTAI
       AND DATALANCAMENTO = P_DATALANCAMENTO
       AND VALOR = P_VALOR
       AND VLJUROS = P_VLJUROS
       AND VLDESCONTO = P_VLDESCONTO
       AND EXCLUIDO = P_EXCLUIDO
       AND ( NUFIN = P_NUFIN
         OR P_NUFIN IS NULL )
       AND ( NUBCO = P_NUBCO
         OR P_NUBCO IS NULL )
       AND ( DTNEG = P_DTNEG
         OR P_DTNEG IS NULL )
       AND ( DTVENC = P_DTVENC
         OR P_DTVENC IS NULL )
       AND ( DHMOV = P_DHMOV
         OR P_DHMOV IS NULL )
       AND ( DTALTER = P_DTALTER
         OR P_DTALTER IS NULL )
       AND ( RECDESP = P_RECDESP
         OR P_RECDESP IS NULL )
       AND ( CODCTABCOINT = P_CODCTABCOINT
         OR P_CODCTABCOINT IS NULL )
       AND ( CODTIPTIT = P_CODTIPTIT
         OR P_CODTIPTIT IS NULL )
       AND ( DESDOBRAMENTO = P_DESDOBRAMENTO
         OR P_DESDOBRAMENTO IS NULL )
       AND ( VLRDESDOB = P_VLRDESDOB
         OR P_VLRDESDOB IS NULL )
       AND ( VLRDESC = P_VLRDESC
         OR P_VLRDESC IS NULL )
       AND ( VLRJUROS = P_VLRJUROS
         OR P_VLRJUROS IS NULL )
       AND ( VLRLANCSNK = P_VLRLANCSNK
         OR P_VLRLANCSNK IS NULL )
       AND ( SALDOSNK = P_SALDOSNK
         OR P_SALDOSNK IS NULL )
       AND ( CODLANC = P_CODLANC
         OR P_CODLANC IS NULL ) )
   WHEN MATCHED THEN
      UPDATE SET ID_CAIXA_MAX = P_ID_CAIXA_MAX
               , ACAO = P_ACAO
               , DHACAO = P_DHACAO
               , CODPRESTACAOCONTAC = P_CODPRESTACAOCONTAC
               , NUMTRANSVENDA = P_NUMTRANSVENDA
               , TIPO = P_TIPO
               , NUMPEDRCA = P_NUMPEDRCA
               , ID_ERP = P_ID_ERP
               , FORMAPAGAMENTO = P_FORMAPAGAMENTO
   WHEN NOT MATCHED THEN
      INSERT ( ID_CAIXA_MAX
             , ACAO
             , DHACAO
             , CODPRESTACAOCONTAC
             , CODPRESTACAOCONTAI
             , DATALANCAMENTO
             , NUMTRANSVENDA
             , TIPO
             , VALOR
             , VLJUROS
             , VLDESCONTO
             , NUMPEDRCA
             , EXCLUIDO
             , ID_ERP
             , FORMAPAGAMENTO
             , NUFIN
             , NUBCO
             , DTNEG
             , DTVENC
             , DHMOV
             , DTALTER
             , RECDESP
             , CODCTABCOINT
             , CODTIPTIT
             , DESDOBRAMENTO
             , VLRDESDOB
             , VLRDESC
             , VLRJUROS
             , VLRLANCSNK
             , SALDOSNK
             , CODLANC )
      VALUES ( P_ID_CAIXA_MAX
             , P_ACAO
             , P_DHACAO
             , P_CODPRESTACAOCONTAC
             , P_CODPRESTACAOCONTAI
             , P_DATALANCAMENTO
             , P_NUMTRANSVENDA
             , P_TIPO
             , P_VALOR
             , P_VLJUROS
             , P_VLDESCONTO
             , P_NUMPEDRCA
             , P_EXCLUIDO
             , P_ID_ERP
             , P_FORMAPAGAMENTO
             , P_NUFIN
             , P_NUBCO
             , P_DTNEG
             , P_DTVENC
             , P_DHMOV
             , P_DTALTER
             , P_RECDESP
             , P_CODCTABCOINT
             , P_CODTIPTIT
             , P_DESDOBRAMENTO
             , P_VLRDESDOB
             , P_VLRDESC
             , P_VLRJUROS
             , P_VLRLANCSNK
             , P_SALDOSNK
             , P_CODLANC );

   COMMIT;
END;
/

/*
NomeObjeto: TRG_INC_MAXIMA_INTEGRA
TipoObjeto: TRIGGER
NomeTabela: AD_MAXIMA_INTEGRA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_INC_MAXIMA_INTEGRA
   BEFORE INSERT
   ON AD_MAXIMA_INTEGRA
   FOR EACH ROW
   WHEN( NEW.ID IS NULL )
BEGIN
   :NEW.ID := SQ_MAXIMA_INTEGRA.NEXTVAL;
END;
/

/*
NomeObjeto: TRG_DLT_TGFCAB_MAXIMA
TipoObjeto: TRIGGER
NomeTabela: TGFCAB
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_DLT_TGFCAB_MAXIMA
   BEFORE DELETE
   ON TGFCAB
   FOR EACH ROW
   WHEN( OLD.AD_MAXIMA_IDPEDIDO IS NOT NULL )
DECLARE
   P_VALIDAR   BOOLEAN;
BEGIN
   IF STP_GET_ATUALIZANDO THEN
      RETURN;
   END IF;

   P_VALIDAR := FPODEVALIDAR( 'TGFCAB' );

   IF ( NOT P_VALIDAR ) THEN
      RETURN;
   END IF;

   INSERT INTO AD_PEDIDO_MAXIMA( NUNOTA
                               , AD_MAXIMA_NUMCAR
                               , AD_MAXIMA_IDPEDIDO
                               , AD_MAXIMA_PEDIDO
                               , PESOBRUTO )
   VALUES ( :OLD.NUNOTA
          , :OLD.AD_MAXIMA_NUMCAR
          , :OLD.AD_MAXIMA_IDPEDIDO
          , :OLD.AD_MAXIMA_PEDIDO
          , :OLD.PESOBRUTO );
END;
/

/*
NomeObjeto: TRG_UPD_TGFCAB_MAXIMA
TipoObjeto: TRIGGER
NomeTabela: TGFCAB
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_UPD_TGFCAB_MAXIMA
   BEFORE INSERT OR UPDATE
   ON TGFCAB
   FOR EACH ROW
DECLARE
   V_COUNT                 INT;
   P_NUMCAR                INT;
   P_VALIDAR               BOOLEAN;
   V_BLOQUEIA_DUPLICACAO   CHAR( 1 );
BEGIN
   /* SE ATUALIZANDO */ 
   IF STP_GET_ATUALIZANDO THEN
      RETURN;
   END IF;

   /* SE NAO PODE VALIDAR */ 
   P_VALIDAR := FPODEVALIDAR( 'TGFCAB' );

   IF ( NOT P_VALIDAR ) THEN
      RETURN;
   END IF;

   --SE EH INSERT
   IF INSERTING THEN
      --SE PEDIDO/NOTA VEIO DA MAXIMA
      IF :NEW.AD_MAXIMA_IDPEDIDO IS NOT NULL THEN
         --SE JA EXISTE NOTA OU PEDIDO COM O MESMO ID ( ESTA DUPLICANDO ), LIMPA OS CAMPOS DE CONTROLE DA MAXIMA
         --OU BLOQUEIA A DUPLICACAO DE ACORDO COM A CONFIGURACAO DO PARAMETRO
         IF SNK_GET_CAB_MAXIMA_EXISTE( :NEW.AD_MAXIMA_IDPEDIDO, :NEW.TIPMOV ) THEN
            --VERIFICA SE DEVE BLOQUEAR A DUPLICACAO
            SELECT NVL( MAX( LOGICO ), 'N' )
              INTO V_BLOQUEIA_DUPLICACAO
              FROM TSIPAR
             WHERE CHAVE = 'BLOQDUPLPDMX';

            --BLOQUEIA A DUPLICACAO
            IF V_BLOQUEIA_DUPLICACAO = 'S' THEN
               RAISE_APPLICATION_ERROR(
                                        -20101
                                      ,
                                        'NAO EH PERMITIDO DUPLICAR PEDIDO/NOTA DE ORIGEM MAXIMA. CAMPO: AD_MAXIMA_IDPEDIDO: '
                                        || :NEW.AD_MAXIMA_IDPEDIDO );
            END IF;

            --SE NAO BLOQUEOU ENTAO LIMPA OS CAMPOS DE CONTROLE DA MAXIMA
            :NEW.AD_MAXIMA_IDPEDIDO := NULL;
            :NEW.AD_MAXIMA_PEDIDO := NULL;
            :NEW.DH_MAXIMA_NUVEM := NULL;
            :NEW.DH_MAXIMA_LANCAMENTO := NULL;
         END IF;
      ELSE
         --LIMPA OS CAMPOS DE CONTROLE DA MAXIMA
         :NEW.AD_MAXIMA_IDPEDIDO := NULL;
         :NEW.AD_MAXIMA_PEDIDO := NULL;
         :NEW.DH_MAXIMA_NUVEM := NULL;
         :NEW.DH_MAXIMA_LANCAMENTO := NULL;
      END IF;
   END IF; --FIM INSERT



   --SE EH UPDATE
   IF UPDATING THEN
      /* SE ESTA RETIRANDO A ORDEM DE CARGA */  
      IF :NEW.TIPMOV = 'P'
     AND NVL( :OLD.ORDEMCARGA, 0 ) <> 0
     AND NVL( :NEW.ORDEMCARGA, 0 ) = 0 THEN
         /* LIMPANDO O NRO DO CARREGAMENTO */  
         :NEW.AD_MAXIMA_NUMCAR := NULL;

         RETURN;
      END IF;

      /* SE ESTA CONFIRMANDO A NOTA E AINDA NAO TEM  NUMERO DE CARREGAMENTO */  
      IF :NEW.TIPMOV = 'V'
     AND :NEW.STATUSNOTA = 'L'
     AND :NEW.AD_MAXIMA_NUMCAR IS NULL THEN
         /* VERIFICANDO SE A TOP EH DE ABASTECIMENTO DE ESTOQUE VEICULO */  
         SELECT COUNT( 1 )
           INTO V_COUNT
           FROM TGFTOP T
          WHERE T.AD_MAXIMA_TIPOVENDA = 13 /* ABASTECIMENTO ESTOQUE VEICULO PRONTA ENTREGA */  
            AND :NEW.TIPMOV = 'V'
            AND T.CODTIPOPER = :NEW.CODTIPOPER
            AND T.DHALTER = :NEW.DHTIPOPER;

         /* SE A TOP NAO EH DE ABASTECIMENTO DE ESTOQUE VEICULO */  
         IF V_COUNT = 0 THEN
            RETURN;
         END IF;

         /* SE O VENDEDOR NAO FOI INFORMADO */  
         IF NVL( :NEW.CODVEND, 0 ) = 0 THEN
            RAISE_APPLICATION_ERROR(
                                     -20101
                                   , 'OBRIGATORIO INFORMAR O VENDEDOR EM NOTA DE REMESSA PARA VENDA FORA DO ESTABELECIMENTO!' );
         END IF;

         /* VERIFICANDO SE JAH TEM CARREGAMENTO ABERTO PARA ESTE VENDEDOR */  
         SELECT NVL( MAX( NUMCAR ), 0 )
           INTO P_NUMCAR
           FROM AD_MAXIMA_CARREGAMENTOS
          WHERE CODVEND = :NEW.CODVEND
            AND DTFECHAMENTO IS NULL;

         /* SE NAO TEM CARREGAMENTO ABERTO */  
         IF P_NUMCAR = 0 THEN
            /* OBTENDO PROXIMO NUMERO DE CARREGAMENTO */  
            SELECT NVL( MAX( NUMCAR ), 0 ) + 1
              INTO P_NUMCAR
              FROM AD_MAXIMA_CARREGAMENTOS;

            /* INSERINDO NOVO CARREGAMENTO */  
            INSERT INTO AD_MAXIMA_CARREGAMENTOS( NUMCAR, CODVEND )
            VALUES ( P_NUMCAR, :NEW.CODVEND );
         END IF;

         /* SETANDO NRO DO CARREGAMENTO NA NOTA */  
         :NEW.AD_MAXIMA_NUMCAR := 'PE' || P_NUMCAR; /* PREFIXO 'PE' IDENTIFICA QUE EH DE PRONTA ENTREGA */  
      END IF;
   END IF; --FIM UPDATE
END;
/

/*
NomeObjeto: TRG_INC_MAXIMA_CAIXA
TipoObjeto: TRIGGER
NomeTabela: AD_CAIXA_MAX
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_INC_MAXIMA_CAIXA
   BEFORE INSERT
   ON AD_CAIXA_MAX
   FOR EACH ROW
   WHEN( NEW.ID IS NULL )
BEGIN
   :NEW.ID := SQ_MAXIMA_CAIXA.NEXTVAL;
END;
/

/*
NomeObjeto: TRG_INC_MAXIMA_MOV_CAIXA
TipoObjeto: TRIGGER
NomeTabela: AD_MOVIMENTOCX_MAX
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_INC_MAXIMA_MOV_CAIXA
   BEFORE INSERT
   ON AD_MOVIMENTOCX_MAX
   FOR EACH ROW
   WHEN( NEW.ID IS NULL )
BEGIN
   :NEW.ID := SQ_MAXIMA_MOV_CAIXA.NEXTVAL;
END;
/

/*
NomeObjeto: TRG_MAXIMA_AD_MAXCONF
TipoObjeto: TRIGGER
NomeTabela: AD_MAXCONF
Executar  : SEMPRE
*/ 

CREATE OR REPLACE TRIGGER TRG_MAXIMA_AD_MAXCONF
   BEFORE INSERT
   ON AD_MAXCONF
   FOR EACH ROW
DECLARE
   V_COUNT   INT;
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   SELECT COUNT( 1 ) INTO V_COUNT FROM AD_MAXCONF;

   IF V_COUNT > 0 THEN
      RAISE_APPLICATION_ERROR(
                               -20101
                             , 'SO EH PERMITIDO UMA LINHA DE CONFIGURACAO!' );
   END IF;

   COMMIT;
END;
/

/*
NomeObjeto: VW_MAXIMA_TRIBUTOS_M
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TRIBUTOS_M
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TRIBUTOS_M AS
   SELECT ROWNUM AS CODST, T.*
     FROM (SELECT CODEMP
                , CODFILIALNF
                , UFDESTINO
                , CODOPER
                , AGREGARIPICALCULOST
                , ALIQICMS1
                , ALIQICMS1FONTE
                , ALIQICMS2
                , ALIQICMS2FONTE
                , CODICM
                , CODICMPF
                , CODICMPRODRURAL
                , CODICMTAB
                , CODICMTABPF
                , IVA
                , IVAFONTE
                , MOSTRARPVENDASEMIPI
                , MOSTRARPVENDASEMST
                , OBS
                , PAUTA
                , PERACRESCIMOFUNCEP
                , PERACRESCIMOPF
                , PERBASEREDNRPA
                , PERCACRESICMSPF_PI
                , PERCBASERED
                , CONSUMIDOR
                , TIPOSN
                , PERCBASEREDST
                , PERCBASEREDSTFONTE
                , PERCBASESTRJ
                , PERCDESCCOFINS
                , PERCDESCPIS
                , PERDESCICMISENCAO
                , PERDESCPISSUFRAMA
                , PERDESCREPASSE
                , PERDESCSUFRAMA
                , RIOLOGISENTOST
                , SITTRIBUT
                , TIPOCALCULOGNRE
                , TV9ISENTOST
                , USAVALORULTENTBASEST
                , USAVALORULTENTBASEST2
                , USAVLULTENTMEDIOBASEST
                , UTILIZAPERCBASEREDPF
                , CODFISCALVENDAPRONTAENT
                , CODFISCALVENDAPRONTAENTINTER
                , CODFISCALBONIFIC
                , CODFISCALBONIFICINTER
                , PRIORIDADE
                , PERCBASEREDCONSUMIDOR
                , PERCREDPVENDASIMPLESNAC
                , PERDIFERIMENTOICMS
                , CODGRUPOTRIBUT
                , ALIQICMSFECP
             FROM TRIBUTACAO_MAXIMA T
            WHERE T.CONSUMIDOR = 'N'
              AND NOT EXISTS
                     (SELECT 1
                        FROM TRIBUTACAO_MAXIMA T2
                       WHERE T2.CODEMP = T.CODEMP
                         AND T2.CODPROD = T.CODPROD
                         AND T2.CODFILIALNF = T.CODFILIALNF
                         AND T2.UFDESTINO = T.UFDESTINO
                         AND T2.CODOPER = T.CODOPER
                         AND T2.CODCLI = T.CODCLI
                         AND T2.CONSUMIDOR = 'S')
           GROUP BY CODEMP
                  , CODFILIALNF
                  , UFDESTINO
                  , CODOPER
                  , AGREGARIPICALCULOST
                  , ALIQICMS1
                  , ALIQICMS1FONTE
                  , ALIQICMS2
                  , ALIQICMS2FONTE
                  , CODICM
                  , CODICMPF
                  , CODICMPRODRURAL
                  , CODICMTAB
                  , CODICMTABPF
                  , IVA
                  , IVAFONTE
                  , MOSTRARPVENDASEMIPI
                  , MOSTRARPVENDASEMST
                  , OBS
                  , PAUTA
                  , PERACRESCIMOFUNCEP
                  , PERACRESCIMOPF
                  , PERBASEREDNRPA
                  , PERCACRESICMSPF_PI
                  , PERCBASERED
                  , CONSUMIDOR
                  , TIPOSN
                  , PERCBASEREDST
                  , PERCBASEREDSTFONTE
                  , PERCBASESTRJ
                  , PERCDESCCOFINS
                  , PERCDESCPIS
                  , PERDESCICMISENCAO
                  , PERDESCPISSUFRAMA
                  , PERDESCREPASSE
                  , PERDESCSUFRAMA
                  , RIOLOGISENTOST
                  , SITTRIBUT
                  , TIPOCALCULOGNRE
                  , TV9ISENTOST
                  , USAVALORULTENTBASEST
                  , USAVALORULTENTBASEST2
                  , USAVLULTENTMEDIOBASEST
                  , UTILIZAPERCBASEREDPF
                  , CODFISCALVENDAPRONTAENT
                  , CODFISCALVENDAPRONTAENTINTER
                  , CODFISCALBONIFIC
                  , CODFISCALBONIFICINTER
                  , PRIORIDADE
                  , PERCBASEREDCONSUMIDOR
                  , PERCREDPVENDASIMPLESNAC
                  , PERDIFERIMENTOICMS
                  , CODGRUPOTRIBUT
                  , ALIQICMSFECP
           UNION
           SELECT CODEMP
                , CODFILIALNF
                , UFDESTINO
                , CODOPER
                , AGREGARIPICALCULOST
                , ALIQICMS1
                , ALIQICMS1FONTE
                , ALIQICMS2
                , ALIQICMS2FONTE
                , CODICM
                , CODICMPF
                , CODICMPRODRURAL
                , CODICMTAB
                , CODICMTABPF
                , IVA
                , IVAFONTE
                , MOSTRARPVENDASEMIPI
                , MOSTRARPVENDASEMST
                , OBS
                , PAUTA
                , PERACRESCIMOFUNCEP
                , PERACRESCIMOPF
                , PERBASEREDNRPA
                , PERCACRESICMSPF_PI
                , PERCBASERED
                , CONSUMIDOR
                , TIPOSN
                , PERCBASEREDST
                , PERCBASEREDSTFONTE
                , PERCBASESTRJ
                , PERCDESCCOFINS
                , PERCDESCPIS
                , PERDESCICMISENCAO
                , PERDESCPISSUFRAMA
                , PERDESCREPASSE
                , PERDESCSUFRAMA
                , RIOLOGISENTOST
                , SITTRIBUT
                , TIPOCALCULOGNRE
                , TV9ISENTOST
                , USAVALORULTENTBASEST
                , USAVALORULTENTBASEST2
                , USAVLULTENTMEDIOBASEST
                , UTILIZAPERCBASEREDPF
                , CODFISCALVENDAPRONTAENT
                , CODFISCALVENDAPRONTAENTINTER
                , CODFISCALBONIFIC
                , CODFISCALBONIFICINTER
                , PRIORIDADE
                , PERCBASEREDCONSUMIDOR
                , PERCREDPVENDASIMPLESNAC
                , PERDIFERIMENTOICMS
                , CODGRUPOTRIBUT
                , ALIQICMSFECP
             FROM TRIBUTACAO_MAXIMA T
            WHERE T.CONSUMIDOR = 'S'
           GROUP BY CODEMP
                  , CODFILIALNF
                  , UFDESTINO
                  , CODOPER
                  , AGREGARIPICALCULOST
                  , ALIQICMS1
                  , ALIQICMS1FONTE
                  , ALIQICMS2
                  , ALIQICMS2FONTE
                  , CODICM
                  , CODICMPF
                  , CODICMPRODRURAL
                  , CODICMTAB
                  , CODICMTABPF
                  , IVA
                  , IVAFONTE
                  , MOSTRARPVENDASEMIPI
                  , MOSTRARPVENDASEMST
                  , OBS
                  , PAUTA
                  , PERACRESCIMOFUNCEP
                  , PERACRESCIMOPF
                  , PERBASEREDNRPA
                  , PERCACRESICMSPF_PI
                  , PERCBASERED
                  , CONSUMIDOR
                  , TIPOSN
                  , PERCBASEREDST
                  , PERCBASEREDSTFONTE
                  , PERCBASESTRJ
                  , PERCDESCCOFINS
                  , PERCDESCPIS
                  , PERDESCICMISENCAO
                  , PERDESCPISSUFRAMA
                  , PERDESCREPASSE
                  , PERDESCSUFRAMA
                  , RIOLOGISENTOST
                  , SITTRIBUT
                  , TIPOCALCULOGNRE
                  , TV9ISENTOST
                  , USAVALORULTENTBASEST
                  , USAVALORULTENTBASEST2
                  , USAVLULTENTMEDIOBASEST
                  , UTILIZAPERCBASEREDPF
                  , CODFISCALVENDAPRONTAENT
                  , CODFISCALVENDAPRONTAENTINTER
                  , CODFISCALBONIFIC
                  , CODFISCALBONIFICINTER
                  , PRIORIDADE
                  , PERCBASEREDCONSUMIDOR
                  , PERCREDPVENDASIMPLESNAC
                  , PERDIFERIMENTOICMS
                  , CODGRUPOTRIBUT
                  , ALIQICMSFECP
                  ) T
/

/*
NomeObjeto: VW_MAXIMA_TRIBUTOS_D
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TRIBUTOS_D
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TRIBUTOS_D AS
   SELECT DISTINCT CODEMP
                 , CODPROD
                 , CODFILIALNF
                 , UFDESTINO
                 , CODOPER
                 , CODCLI
                 , CODGRUPOTRIBUT
     FROM TRIBUTACAO_MAXIMA T
/

/*
NomeObjeto: VW_MAXIMA_CONTAS_BANCARIAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CONTAS_BANCARIAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CONTAS_BANCARIAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 39 )
                     AS MD5
                , SNK_GET_MD5( T.CODCONTA || T.CODBANCO || T.AG || T.NUMCONTA
                              || T.CODFILIAL || T.DESCRICAO || T.TIPO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODCTABCOINT ) AS CHAVE
                        , CODCTABCOINT AS CODCONTA
                        , CODBCO AS CODBANCO
                        , CODAGE AS AG
                        , CODCTABCO AS NUMCONTA
                        , CODEMP AS CODFILIAL
                        , DESCRICAO AS DESCRICAO
                        , CLASSE AS TIPO
                     FROM TSICTA
                    WHERE AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_CODIGO_FISCAL
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CODIGO_FISCAL
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CODIGO_FISCAL AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 55 )
                     AS MD5
                , SNK_GET_MD5( T.CODFISCAL || T.DESCCFO ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODCFO ) AS CHAVE
                        , CODCFO AS CODFISCAL
                        , DESCRCFO AS DESCCFO
                     FROM TGFCFO) T) T2
/

/*
NomeObjeto: VW_MAXIMA_NATUREZAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_NATUREZAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_NATUREZAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 37 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCATEGORIADESPESA || T.DESCRICAO || T.
                               ATIVO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( NAT.CODNAT ) AS CHAVE
                        , NAT.CODNAT AS CODCATEGORIADESPESA
                        , NAT.DESCRNAT AS DESCRICAO
                        , NAT.ATIVA AS ATIVO
                     FROM TGFNAT NAT
                    WHERE NAT.ANALITICA = 'S'
                      AND NAT.AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_PLANO_PGTO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PLANO_PGTO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PLANO_PGTO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 24 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODTIPVENDA || T.DESCRTIPVENDA || T.
                               EMITEBOLETA || T.PRAZOMAX || T.VENDAMIN || T.
                               PRAZOMEDMAX || T.NROPARCELAS || T.CODTAB || T
                               .TIPOPRAZO || T.VLMINPEDIDO || T.TIPOENTRADA
                               || T.TIPOVENDA || T.VENDABK || T.PERTXFIM )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( TPV.CODTIPVENDA ) AS CHAVE
                        , TPV.CODTIPVENDA
                        , TPV.DESCRTIPVENDA
                        , TPV.EMITEBOLETA
                        , TPV.PRAZOMAX
                        , TPV.VENDAMIN
                        , TPV.PRAZOMEDMAX
                        , TPV.NROPARCELAS
                        , TPV.CODTAB
                        , 'N' AS TIPOPRAZO
                        , VENDAMIN AS VLMINPEDIDO
                        , CASE
                             WHEN TPV.SUBTIPOVENDA = 1 THEN 10
                             ELSE NULL
                          END
                             AS TIPOENTRADA
                        , CASE
                             WHEN TPV.SUBTIPOVENDA = 1 THEN 'VV'
                             ELSE 'VP'
                          END
                             AS TIPOVENDA
                        , CASE
                             WHEN ( SELECT COUNT( 1 )
                                     FROM TGFPPG PPG, TGFTIT TIT
                                    WHERE PPG.CODTIPVENDA = TPV.CODTIPVENDA
                                      AND TIT.CODTIPTIT = PPG.CODTIPTITPAD
                                      AND TIT.ESPDOC IN ('B', 'BO') ) > 0 THEN
                                'S'
                             ELSE
                                'N'
                          END
                             AS VENDABK
                        , NVL(TPV.TAXAJURO,0) * CASE WHEN TIPTAXA <> 'U' THEN -1 ELSE 1 END AS PERTXFIM
                     FROM TGFTPV TPV
                    WHERE TPV.AD_MAXIMA = 'S'
                      AND TPV.ATIVO = 'S'
                      AND TPV.CODTIPVENDA <> 0
                      AND TPV.DHALTER =
                             (SELECT MAX( DHALTER )
                                FROM TGFTPV T2
                               WHERE T2.CODTIPVENDA = TPV.CODTIPVENDA)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_PRACA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRACA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRACA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 12 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODPRACA || T.NUMREGIAO || T.ROTA || T.
                               SITUACAO || T.PRACA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( NTA.CODTAB ) AS CHAVE
                        , NTA.CODTAB AS CODPRACA
                        , NTA.CODTAB AS NUMREGIAO
                        , 1 AS ROTA
                        , CASE WHEN NTA.ATIVO = 'S' THEN 'A' ELSE 'I' END
                             AS SITUACAO
                        , NTA.NOMETAB AS PRACA
                     FROM TGFNTA NTA
                    WHERE NTA.AD_MAXIMA = 'S'
                      AND EXISTS
                             (SELECT 1
                                FROM TGFTAB TAB
                               WHERE TAB.CODTAB = NTA.CODTAB
                                 AND TAB.NUTAB =
                                        ( SELECT MAX( T.NUTAB )
                                           FROM TGFTAB T
                                          WHERE T.CODTAB = TAB.CODTAB
                                            AND T.DTVIGOR =
                                                   ( SELECT MAX( T2.DTVIGOR )
                                                      FROM TGFTAB T2
                                                     WHERE T2.CODTAB =
                                                              TAB.CODTAB
                                                       AND T2.DTVIGOR <=
                                                              TRUNC(
                                                                     SYSDATE ) ) ))) T) T2
/

/*
NomeObjeto: VW_MAXIMA_REGIAO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_REGIAO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_REGIAO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 2 )
                     AS MD5
                , SNK_GET_MD5( T.NUMREGIAO || T.REGIAO || T.STATUS )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( NTA.CODTAB ) AS CHAVE
                        , NTA.CODTAB AS NUMREGIAO
                        , NTA.NOMETAB AS REGIAO
                        , CASE WHEN NTA.ATIVO = 'S' THEN 'A' ELSE 'I' END
                             AS STATUS
                        , ( SELECT UF
                             FROM TSIUFS
                            WHERE CODUF =
                                     ( SELECT UF
                                        FROM TSICID
                                       WHERE CODCID =
                                                (SELECT CODCID
                                                   FROM TSIEMP
                                                  WHERE CODEMP = EMP.CODEMP) ) )
                             AS UF
                        , EMP.CODEMP AS CODFILIAL
                        , TB.NUMTABELA
                        , TB.CODREPRESENTANTE
                        , TB.CODESTABELECIMENTO
                     FROM TGFNTA NTA
                        , (SELECT MIN( CODEMP ) AS CODEMP
                             FROM TSIEMP
                            WHERE AD_MAXIMA = 'S') EMP
                        , (SELECT AD_NUMTABELA AS NUMTABELA
                           , AD_CODREPRESENTANTE AS  CODREPRESENTANTE
                           , AD_CODESTABELECIMENTO AS CODESTABELECIMENTO
                           , T1.NUTAB
                           FROM TGFTAB T1 WHERE T1.NUTAB = ( SELECT MAX( T2.NUTAB )
                                           FROM TGFTAB T2
                                          WHERE T1.CODTAB = T2.CODTAB
                                            AND T2.DTVIGOR =
                                                   ( SELECT MAX( T3.DTVIGOR )
                                                      FROM TGFTAB T3
                                                     WHERE T3.CODTAB = T2.CODTAB
                                                       AND T3.DTVIGOR <= TRUNC( SYSDATE ) ) )) TB
                    WHERE NTA.AD_MAXIMA = 'S'
                      AND EXISTS
                             (SELECT 1
                                FROM TGFTAB TAB
                               WHERE TAB.CODTAB = NTA.CODTAB
                                 AND TAB.NUTAB = TB.NUTAB)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_PROD_FILIAIS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROD_FILIAIS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROD_FILIAIS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 11 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODFILIAL || T.CODPROD || T.PROIBIDAVENDA ||
                               T.ENVIARFORCAVENDAS || T.MULTIPLO )
                     AS MD5LINHA
                , T.*
             FROM ( /* PRODUTOS POR EMPRESA - TGFPEM */  
                   SELECT DISTINCT
                          TO_CHAR(
                   LPAD            ( PEM.CODEMP, 5, 0 ) || LPAD( PEM.CODPROD
                   , 10, 0 ) )
                      AS CHAVE
                        ,PEM.CODEMP AS CODFILIAL
                        ,PEM.CODPROD
                        ,'N' AS PROIBIDAVENDA
                        ,'S' AS ENVIARFORCAVENDAS
                        ,P.AGRUPMIN AS MULTIPLO
                     FROM TGFPEM PEM, TGFPRO P, TSIEMP E
                    WHERE PEM.CODPROD = P.CODPROD
                      AND PEM.CODEMP = E.CODEMP
                      AND P.AD_MAXIMA = 'S'
                      AND E.AD_MAXIMA = 'S'
                      AND NOT EXISTS
                      (   SELECT 1
                            FROM AD_MAXIMA_PRODFILIAL
                           WHERE CODPROD = P.CODPROD)
                   UNION
                   /* PRODUTOS SEM EXCECAO POR EMPRESA */  
                   SELECT DISTINCT
                          LPAD( E.CODEMP, 5, 0 ) || LPAD( P.CODPROD, 10, 0 )
                      AS CHAVE
                        ,E.CODEMP AS CODFILIAL
                        ,P.CODPROD
                        ,'N' AS PROIBIDAVENDA
                        ,'S' AS ENVIARFORCAVENDAS
                        ,P.AGRUPMIN AS MULTIPLO
                     FROM TGFPRO P, TSIEMP E
                    WHERE P.AD_MAXIMA = 'S'
                      AND E.AD_MAXIMA = 'S'
                      AND NOT EXISTS
                      (   SELECT 1
                            FROM AD_MAXIMA_PRODFILIAL
                           WHERE CODPROD = P.CODPROD)
                   UNION
                   /* PRODUTOS COM EXCECAO POR EMPRESA */  
                   SELECT DISTINCT
                          LPAD( E.CODEMP, 5, 0 ) || LPAD( P.CODPROD, 10, 0 )
                      AS CHAVE
                        ,E.CODEMP AS CODFILIAL
                        ,P.CODPROD
                        ,'N' AS PROIBIDAVENDA
                        ,'S' AS ENVIARFORCAVENDAS
                        ,P.AGRUPMIN AS MULTIPLO
                     FROM AD_MAXIMA_PRODFILIAL PF, TGFPRO P, TSIEMP E
                    WHERE P.AD_MAXIMA = 'S'
                      AND E.AD_MAXIMA = 'S'
                      AND PF.CODEMP = E.CODEMP
                      AND PF.CODPROD = P.CODPROD) T) T2
/

/*
NomeObjeto: VW_MAXIMA_VENDEDOR
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VENDEDOR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VENDEDOR AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 7 )
                     AS MD5
                , SNK_GET_MD5(
                               T.BLOQUEIO || T.CODSUPERVISOR || T.CODUSUR ||
                               T.EMAIL || T.NOME || T.TELEFONE1 || T.TIPOVEND
                               || T.USADEBCREDRCA || T.CODFILIAL || T.
                               CODCLIRCA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( VEN.CODVEND ) AS CHAVE
                        , CASE WHEN VEN.ATIVO = 'S' THEN 'N' ELSE 'S' END
                             AS BLOQUEIO
                        , NVL( VEN.CODGER, 1 ) AS CODSUPERVISOR
                        , VEN.CODVEND AS CODUSUR
                        , VEN.EMAIL AS EMAIL
                        , VEN.APELIDO AS NOME
                        , NVL( ( SELECT TELEFONE
                                  FROM TGFPAR P
                                 WHERE P.CODPARC = VEN.CODPARC )
                             , '<SEM TELEFONE>' )
                             AS TELEFONE1
                        , 'E' AS TIPOVEND
                        , 'S' AS USADEBCREDRCA
                        , VEN.CODEMP AS CODFILIAL
                        , VEN.CODPARC AS CODCLIRCA
                     FROM TGFVEN VEN
                    WHERE VEN.AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_SUPERVISOR
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SUPERVISOR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SUPERVISOR AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 8 )
                     AS MD5
                , SNK_GET_MD5( T.CODSUPERVISOR || T.NOME || T.POSICAO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( VEN.CODVEND ) AS CHAVE
                        , VEN.CODVEND AS CODSUPERVISOR
                        , VEN.APELIDO AS NOME
                        , CASE WHEN VEN.ATIVO = 'S' THEN 'A' ELSE 'I' END
                             AS POSICAO
                        , VEN.CODVEND AS COD_CADRCA
                     FROM TGFVEN VEN
                    WHERE VEN.AD_MAXIMA = 'S'
                      AND VEN.TIPVEND IN ('G', 'S')) T) T2
/

/*
NomeObjeto: VW_MAXIMA_MARCA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MARCA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MARCA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 23 )
                     AS MD5
                , SNK_GET_MD5( T.CODMARCA || T.MARCA ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODIGO ) AS CHAVE
                        , CODIGO AS CODMARCA
                        , DESCRICAO AS MARCA
                     FROM TGFMAR MAR) T) T2
/

/*
NomeObjeto: VW_MAX_PLANO_PGTO_CLIE
TipoObjeto: VIEW
NomeTabela: VW_MAX_PLANO_PGTO_CLIE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_PLANO_PGTO_CLIE AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 29 )
                     AS MD5
                , SNK_GET_MD5( T.CODPARC || T.CODTIPVENDA ) AS MD5LINHA
                , T.*
             FROM (SELECT DISTINCT
                          TO_CHAR(
                                   LPAD( PAR.CODPARC, 10, 0 ) || LPAD(
                                   TPV.CODTIPVENDA
                                                                     ,5
                                                                     ,0 ) )
                             AS CHAVE
                        , PAR.CODPARC
                        , TPV.CODTIPVENDA
                     FROM TGFTPV TPV, TGFPAR PAR
                    WHERE PAR.GRUPOAUTOR LIKE
                             ( '%' || TPV.GRUPOAUTOR || '%' )
                      AND TPV.GRUPOAUTOR IS NOT NULL
                      AND PAR.CLIENTE = 'S'
                      AND PAR.AD_MAXIMA_CLIENTE = 'S'
                      AND TPV.AD_MAXIMA = 'S'
                      AND TPV.CODTIPVENDA <> 0
                      AND TPV.DHALTER =
                             (SELECT MAX( DHALTER )
                                FROM TGFTPV T2
                               WHERE T2.CODTIPVENDA = TPV.CODTIPVENDA)
                      AND EXISTS
                             (SELECT 1
                                FROM TGFVEN V
                               WHERE V.CODVEND = PAR.CODVEND
                                 AND V.AD_MAXIMA = 'S')) T) T2
/

/*
NomeObjeto: VW_MAXIMA_COBRANCAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_COBRANCAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_COBRANCAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 9 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCOB || T.COBRANCA || T.BOLETO || T.CARTAO
                               || T.CODFILIAL || T.NIVELVENDA || T.
                               PRAZOMAXIMOVENDA ||  T.
                               TXJUROS || T.PERCMULTA || T.TIPOCOBRANCA || T
                               .VLMINPEDIDO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( LPAD( TIT.CODTIPTIT, 5, 0 ) ) AS CHAVE
                        , TIT.CODTIPTIT AS CODCOB
                        , TIT.DESCRTIPTIT AS COBRANCA
                        , CASE WHEN TIT.ESPDOC = 'BO' THEN 'S' ELSE 'N' END
                             AS BOLETO
                        , CASE WHEN TIT.ESPDOC = 'CC' THEN 'S' ELSE 'N' END
                             CARTAO
                        , NULL AS CODFILIAL
                        , 0 AS NIVELVENDA
                        , 9999 AS PRAZOMAXIMOVENDA
                        , PERCJUROS AS TXJUROS
                        , PERCMULTA AS PERCMULTA
                        , TIT.ESPDOC AS TIPOCOBRANCA
                        , 0 AS VLMINPEDIDO
                        , AD_COBRANCABROKER AS COBRANCABROKER
                     FROM TGFTIT TIT
                    WHERE TIT.AD_MAXIMA = 'S'
                      AND TIT.ATIVO = 'S'
                      AND TIT.CODTIPTIT <> 0) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CLIENTESCREDITOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CLIENTESCREDITOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CLIENTESCREDITOS AS
   SELECT *
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE TIPO = 17
                      AND CHAVE = T2.CHAVE )
                     AS MD5
                , SNK_GET_MD5(
                               T2.CODCLI || T2.NOMEPARC || T2.VLLIMITE || T2
                               .VLTITULOS )
                     AS MD5LINHA
                , T2.*
             FROM (SELECT T.*
                        , DEBITO_1 + DEBITO_2 + DEBITO_3 + DEBITO_4
                             AS VLTITULOS
                     FROM (SELECT TO_CHAR( CODPARC ) AS CHAVE
                                , CODPARC AS CODCLI
                                , NOMEPARC
                                , NVL( PAR.LIMCRED, 0 ) AS VLLIMITE
                                , ( SELECT NVL( SUM( F.VLRDESDOB ), 0 )
                                              AS DEBITO
                                     FROM TGFFIN F
                                        , (SELECT LOGICO AS LIMCREDMATRIZ
                                             FROM TSIPAR
                                            WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA IS NULL
                                      AND F.PROVISAO <> 'S'
                                      AND F.RECDESP = 1
                                      AND NOT EXISTS
                                                 (SELECT 1
                                                    FROM TGFTIT T
                                                   WHERE T.CODTIPTIT =
                                                            F.CODTIPTIT
                                                     AND T.SUBTIPOVENDA = 7)
                                      AND F.CODPARC = PAR.CODPARC )
                                     AS DEBITO_1
                                , ( SELECT NVL( SUM( F.VLRDESDOB ), 0 )
                                              AS DEBITO
                                     FROM TGFFIN F
                                        , (SELECT LOGICO AS LIMCREDMATRIZ
                                             FROM TSIPAR
                                            WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA > TRUNC( SYSDATE )
                                      AND F.PROVISAO <> 'S'
                                      AND F.RECDESP = 1
                                      AND NOT EXISTS
                                                 (SELECT 1
                                                    FROM TGFTIT T
                                                   WHERE T.CODTIPTIT =
                                                            F.CODTIPTIT
                                                     AND T.SUBTIPOVENDA = 7)
                                      AND F.CODPARC = PAR.CODPARC )
                                     AS DEBITO_2
                                , ( SELECT NVL( SUM( F.VLRDESDOB ), 0 )
                                              AS DEBITO
                                     FROM TGFFIN F
                                        , (SELECT LOGICO AS LIMCREDMATRIZ
                                             FROM TSIPAR
                                            WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA IS NULL
                                      AND F.PROVISAO <> 'S'
                                      AND F.RECDESP = 1
                                      AND NOT EXISTS
                                                 (SELECT 1
                                                    FROM TGFTIT T
                                                   WHERE T.CODTIPTIT =
                                                            F.CODTIPTIT
                                                     AND T.SUBTIPOVENDA = 7)
                                      AND PARAM.LIMCREDMATRIZ = 'S'
                                      AND F.CODPARC IN
                                             ( SELECT CODPARC
                                                FROM TGFPAR P
                                               WHERE P.CODPARCMATRIZ =
                                                        PAR.CODPARCMATRIZ ) )
                                     AS DEBITO_3
                                , ( SELECT NVL( SUM( F.VLRDESDOB ), 0 )
                                              AS DEBITO
                                     FROM TGFFIN F
                                        , (SELECT LOGICO AS LIMCREDMATRIZ
                                             FROM TSIPAR
                                            WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA > TRUNC( SYSDATE )
                                      AND F.PROVISAO <> 'S'
                                      AND F.RECDESP = 1
                                      AND NOT EXISTS
                                                 (SELECT 1
                                                    FROM TGFTIT T
                                                   WHERE T.CODTIPTIT =
                                                            F.CODTIPTIT
                                                     AND T.SUBTIPOVENDA = 7)
                                      AND PARAM.LIMCREDMATRIZ = 'S'
                                      AND F.CODPARC IN
                                             ( SELECT CODPARC
                                                FROM TGFPAR P
                                               WHERE P.CODPARCMATRIZ =
                                                        PAR.CODPARCMATRIZ ) )
                                     AS DEBITO_4
                                , 0 AS VLPEDIDOS
                                , 0 AS VLCHEQUES
                                , 0 AS VLCREDITO
                                , 0 AS VLLIMITECREDSUPPLI
                             FROM TGFPAR PAR
                            WHERE PAR.AD_MAXIMA_CLIENTE = 'S'
                              AND PAR.CLIENTE = 'S') T) T2) T3
/

/*
NomeObjeto: VW_MAX_CLIENTESENDERECOS
TipoObjeto: VIEW
NomeTabela: VW_MAX_CLIENTESENDERECOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_CLIENTESENDERECOS AS
SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 14 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCLI || T.CODENDENTCLI || T.CODBAIRROENT
                               || T.BAIRROENT || T.ESTENT || T.CEPENT || T.
                               ENDERENT || T.COMPLEMENTOENT || T.CODPRACAENT
                               || T.NUMEROENT || T.MUNICENT )
                     AS MD5LINHA
                , T.*
             FROM (SELECT /* ENDERECO DE ENTREGA DOS CONTATOS */  
                         TO_CHAR(
                                  LPAD( CTT.CODCONTATO, 10, 0 ) || LPAD(
                                  PAR.CODPARC
                                                                       ,10
                                                                       ,0 ) )
                             AS CHAVE
                        , PAR.CODPARC AS CODCLI
                        , LPAD( CTT.CODCONTATO, 10, 0 ) || LPAD( PAR.CODPARC
                          , 10, 0 )
                             AS CODENDENTCLI
                        , CTT.CODBAI AS CODBAIRROENT
                        , ( SELECT NOMEBAI
                             FROM TSIBAI
                            WHERE TSIBAI.CODBAI = CTT.CODBAI )
                             AS BAIRROENT
                        , ( SELECT UF
                             FROM TSIUFS
                            WHERE TSIUFS.CODUF =
                                     (SELECT UF
                                        FROM TSICID
                                       WHERE TSICID.CODCID = CTT.CODCID) )
                             AS ESTENT
                        , CTT.CEP AS CEPENT
                        , ( SELECT NOMEEND
                             FROM TSIEND
                            WHERE TSIEND.CODEND = CTT.CODEND )
                             AS ENDERENT
                        , PAR.COMPLEMENTO AS COMPLEMENTOENT
                        , 0 AS CODPRACAENT
                        , CTT.NUMEND AS NUMEROENT
                        , ( SELECT NOMECID
                             FROM TSICID
                            WHERE TSICID.CODCID = CTT.CODCID )
                             AS MUNICENT
                     FROM TGFCTT CTT, TGFPAR PAR
                    WHERE PAR.AD_MAXIMA_CLIENTE = 'S'
                      AND PAR.CLIENTE = 'S'
                      AND PAR.ENTREGAENDCONTATO = 'S'
                      AND CTT.CODPARC = PAR.CODPARC) T) T2
/

/*
NomeObjeto: VW_MAXIMA_EMPRESA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_EMPRESA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_EMPRESA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 10 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODEMP || T.RAZAOSOCIAL || T.CGC || T.
                               INSCESTAD || T.ENDERECO || T.BAIRRO || T.UF ||
                               T.CIDADE || T.TELEFONE || T.FAX || T.
                               UTILIZA_VENDA_POR_EMBALAGEM || T.TRABCOMIPI ||
                               T.CODPARC || T.UTILIZAWMS || T.ATIVO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( EMP.CODEMP ) AS CHAVE
                        , EMP.CODEMP
                        , EMP.RAZAOSOCIAL
                        , EMP.CGC
                        , EMP.INSCESTAD
                        , EMP.CODEND AS ENDERECO
                        , EMP.CODBAI AS BAIRRO
                        , ( SELECT UFS.UF
                             FROM TSIUFS UFS, TSICID CID
                            WHERE UFS.CODUF = CID.UF
                              AND EMP.CODCID = CID.CODCID )
                             AS UF
                        , EMP.CODCID AS CIDADE
                        , EMP.TELEFONE
                        , EMP.FAX
                        , EMP.AD_MAXIMA_VENDA_EMB
                             AS UTILIZA_VENDA_POR_EMBALAGEM
                        , NVL( ( SELECT TRABCOMIPI
                                  FROM TGFEMP TGF
                                 WHERE TGF.CODEMP = EMP.CODEMP )
                             , 'N' )
                             AS TRABCOMIPI
                        , EMP.CODPARC
                        , NVL( ( SELECT UTILIZAWMS
                                  FROM TGFEMP TGF
                                 WHERE TGF.CODEMP = EMP.CODEMP )
                             , 'N' )
                             AS UTILIZAWMS
                        , ( SELECT ATIVO
                             FROM TGFEMP
                            WHERE TGFEMP.CODEMP = EMP.CODEMP )
                             AS ATIVO
                        , AD_BROKER AS BROKER     
                     FROM TSIEMP EMP
                    WHERE EMP.AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_TITULOS_ABERTO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TITULOS_ABERTO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TITULOS_ABERTO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 19 )
                     AS MD5
                , SNK_GET_MD5(
                               T.VALORDESC || T.CODCLI || T.VLRJURO || T.
                               CODFILIAL || T.VALOR || T.ATRASO || T.PREST ||
                               TO_CHAR
                               ( T.DTVENCORIG, 'YYYY-MM-DD HH24:MI:SS' ) ||
                               T.CODUSUR || T.NUMCHEQUE || TO_CHAR( T.DTVENC
                               , 'YYYY-MM-DD HH24:MI:SS' ) || T.VALORORIG ||
                               TO_CHAR
                               ( T.DTEMISSAO, 'YYYY-MM-DD HH24:MI:SS' ) || T
                               .CODCOB || T.DUPLIC || TO_CHAR( T.DTPAG
                                                             ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.VLRMULTA || T.
                               CARTORIO || T.PROTESTO || T.RECEBIVEL || T.
                               AGENCIA || T.NUMBANCO || T.NUMCARTEIRA || T.
                               CODCLIENTENOBANCO || T.CODBARRA || T.LINHADIG
                               || T.NOSSONUMBCO || T.NUMTRANSVENDA || T.
                               ID_ERP )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( FIN.NUFIN ) AS CHAVE
                        , FIN.VLRDESC AS VALORDESC
                        , FIN.CODPARC AS CODCLI
                        , FIN.VLRJURO AS VLRJURO
                        , FIN.CODEMP AS CODFILIAL
                        , FIN.VLRDESDOB * NVL( FIN.RECDESP, 0 ) AS VALOR
                        , TRUNC( CASE
                                   WHEN FIN.DTVENC IS NULL THEN
                                      0
                                   ELSE
                                      ( CASE
                                          WHEN FIN.DHBAIXA IS NOT NULL
                                           AND FIN.VLRBAIXA <> 0 THEN
                                             FIN.DHBAIXA - FIN.DTVENC
                                          ELSE
                                             SYSDATE - FIN.DTVENC
                                       END )
                                END )
                             AS ATRASO
                        , CASE
                             WHEN FIN.NUNOTA IS NOT NULL THEN
                                CAST(
                                      NVL( FIN.DESDOBRAMENTO, 0 ) AS VARCHAR( 4 ) )
                             ELSE
                                'T' || NVL( FIN.DESDOBRAMENTO, 0 )
                          END
                             AS PREST
                        , FIN.DTVENCINIC AS DTVENCORIG
                        , NVL( FIN.CODVEND, 0 ) AS CODUSUR
                        , FIN.NUCHQ AS NUMCHEQUE
                        , FIN.DTVENC AS DTVENC
                        , ( NVL( FIN.VLRDESDOB, 0 ) + ( CASE
                             WHEN FIN.TIPMULTA = '1' THEN
                             NVL( FIN.VLRMULTA, 0 )
                             ELSE
                             0
                          END ) + ( CASE
                             WHEN FIN.TIPJURO = '1' THEN
                             NVL( FIN.VLRJURO, 0 )
                             ELSE
                             0
                          END ) + NVL( FIN.DESPCART, 0 ) + NVL( FIN.VLRVENDOR
                                                              ,0 ) - NVL(
                          FIN.VLRDESC
                                                                        ,0 )
                          - ( CASE
                             WHEN FIN.IRFRETIDO = 'S' THEN
                             NVL( FIN.VLRIRF, 0 )
                             ELSE
                             0
                          END ) - ( CASE
                             WHEN FIN.ISSRETIDO = 'S' THEN
                             NVL( FIN.VLRISS, 0 )
                             ELSE
                             0
                          END ) - ( CASE
                             WHEN FIN.INSSRETIDO = 'S' THEN
                             NVL( FIN.VLRINSS, 0 )
                             ELSE
                             0
                          END ) - NVL( FIN.CARTAODESC, 0 ) + NVL(
                          (                                       SELECT SUM
                          ( I.VALOR * I.TIPIMP )
                                                                    FROM
                          TGFIMF I
                                                                   WHERE I.
                          NUFIN = FIN.NUFIN )
                                                                ,0 ) + NVL(
                          FIN.VLRMULTANEGOC
                                                                          ,0
                          ) + NVL( FIN.VLRJURONEGOC, 0 ) - NVL(
                          FIN.VLRMULTALIB
                                                              ,0 ) - NVL(
                          FIN.VLRJUROLIB
                                                                        ,0 )
                          + NVL( FIN.VLRVARCAMBIAL, 0 ) ) * NVL( FIN.RECDESP
                                                               ,0 )
                             AS VALORORIG
                        , FIN.DTNEG AS DTEMISSAO
                        , FIN.CODTIPTIT AS CODCOB
                        , NVL( FIN.NUMDUPL, 0 ) AS DUPLIC
                        , FIN.DHBAIXA AS DTPAG
                        , FIN.DHBAIXA AS DTBAIXA
                        , FIN.VLRMULTA AS VLRMULTA
                        , CASE
                             WHEN EXISTS
                                     (SELECT 1
                                        FROM AD_MAXCONF
                                       WHERE TIT_CARTORIO = FIN.CODTIPTIT) THEN
                                'S'
                             ELSE
                                'N'
                          END
                             AS CARTORIO
                        , CASE
                             WHEN EXISTS
                                     (SELECT 1
                                        FROM AD_MAXCONF
                                       WHERE TIT_PROTESTO = FIN.CODTIPTIT) THEN
                                'S'
                             ELSE
                                'N'
                          END
                             AS PROTESTO
                        , NVL( FIN.AD_MAXIMA_RECEBE, 'N' ) AS RECEBIVEL
                        , CTA.CODAGE AS AGENCIA
                        , LPAD( CTA.CODBCO, 3, '0' ) AS NUMBANCO
                        , CTA.CARTEIRA AS NUMCARTEIRA
                        , CTA.CODCTABENEF AS CODCLIENTENOBANCO
                        , FIN.CODIGOBARRA AS CODBARRA
                        , FIN.LINHADIGITAVEL AS LINHADIG
                        , NVL( FIN.NOSSONUM, 0 ) AS NOSSONUMBCO
                        , NVL( FIN.NUNOTA, FIN.NUFIN ) AS NUMTRANSVENDA
                        , FIN.NUFIN AS ID_ERP
                     FROM TGFFIN FIN
                          LEFT JOIN TSICTA CTA
                             ON CTA.CODCTABCOINT = FIN.CODCTABCOINT
                    WHERE ( FIN.RECDESP = 1
                        OR FIN.RECDESP = -1
                       AND EXISTS
                              (SELECT 1
                                 FROM TGFVEN V
                                WHERE V.CODPARC = FIN.CODPARC) )
                      AND FIN.PROVISAO = 'N'
                      AND EXISTS
                             (SELECT 1
                                FROM TGFPAR PAR
                               WHERE PAR.CODPARC = FIN.CODPARC
                                 AND PAR.CLIENTE = 'S'
                                 AND PAR.AD_MAXIMA_CLIENTE = 'S')
                      AND ( EXISTS
                              (SELECT 1
                                 FROM TGFVEN VEN
                                WHERE VEN.CODVEND = FIN.CODVEND
                                  AND VEN.AD_MAXIMA = 'S')
                        OR EXISTS
                              (SELECT 1
                                 FROM TGFVEN V
                                WHERE V.CODPARC = FIN.CODPARC) )) T) T2
/

/*
NomeObjeto: VW_PEDIDOS_MAXIMA
TipoObjeto: VIEW
NomeTabela: VW_PEDIDOS_MAXIMA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_PEDIDOS_MAXIMA AS
--PEDIDOS NORMAIS
SELECT CAB.NUNOTA  
        ,CAB.ORDEMCARGA
        ,CASE WHEN CAB.PENDENTE = 'N' AND ( SELECT COUNT(1) FROM TGFVAR V WHERE V.NUNOTAORIG = CAB.NUNOTA ) = 0 THEN 'C' ELSE CAB.PENDENTE END AS PENDENTE
        ,CAB.STATUSNOTA
        ,CAST( CAB.OBSERVACAO AS VARCHAR( 400 ) ) AS MOTIVO
        ,CAB.CODPARC AS CODCLI
        ,CAB.PESOBRUTO AS TOTPESO
        ,CAB.NUNOTA AS NUMPED
        ,CAB.AD_MAXIMA_PEDIDO AS NUMPEDRCA
        ,CAB.CODEMP AS CODFILIAL
        ,CAB.CODVEND AS CODUSUR
        ,CAB.VLRNOTA AS VLTOTAL
        ,CAB.DTNEG AS DATA
        ,CAB.OBSERVACAO AS OBS1
        ,CAB.CODPARCTRANSP AS CODFORNECFRETE
        ,CAB.OBSERVACAO AS OBS
        ,CAB.CODTIPVENDA AS CODPLPAG
        ,CASE WHEN INSTR(CAB.AD_MAXIMA_NUMCAR, 'PE') > 0 THEN CAB.AD_MAXIMA_NUMCAR
         WHEN CAB.ORDEMCARGA IS NOT NULL AND EXISTS( SELECT 1 FROM TGFORD O WHERE O.CODEMP = CAB.CODEMP AND O.ORDEMCARGA = CAB.ORDEMCARGA AND O.AD_MAXIMA_NUMCAR IS NOT NULL)
            THEN(SELECT MAX( AD_MAXIMA_NUMCAR ) FROM TGFORD O WHERE O.CODEMP = CAB.CODEMP AND O.ORDEMCARGA = CAB.ORDEMCARGA )
         WHEN CAB.ORDEMCARGA IS NOT NULL 
            THEN 'OC' || TO_CHAR(LPAD( CAB.CODEMP, 5, 0 ) || LPAD( CAB.ORDEMCARGA, 10, 0 ))
         ELSE NULL END AS NUMCAR
        ,CAB.AD_MAXIMA_IDPEDIDO AS ID_PEDIDO
        ,CAB.CODTIPOPER
        ,CAB.DHTIPOPER
        , SNK_GET_NOTA_MAXIMA( CAB.NUNOTA ) AS NUNOTA_NOTA
        , CASE 
            WHEN CAB.CODCONTATOENTREGA IS NOT NULL OR CAB.CODCONTATO IS NOT NULL THEN 
                  LPAD( NVL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ), 10, 0 ) || LPAD( CAB.CODPARC , 10, 0 )
            ELSE
                  NULL
            END
         AS CODENDENTCLI      
     FROM TGFCAB CAB
        ,(SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM AD_MAXCONF) CONF
        ,TGFTOP TOP
    WHERE CAB.TIPMOV = 'P'
      AND CAB.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_HIST_VENDAS
      AND CAB.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
      AND TOP.CODTIPOPER = CAB.CODTIPOPER
      AND TOP.DHALTER = CAB.DHTIPOPER
      AND TOP.AD_ENVIARMAXIMA = 'S'
   UNION   --PEDIDOS CANCELADOS QUE VIERAM DA MÁXIMA
   SELECT CAB.NUNOTA
        ,CAB.ORDEMCARGA
        ,'C' AS PENDENTE --CANCELADO
        ,CAB.STATUSNOTA
        ,CAST( CAB.OBSERVACAO AS VARCHAR( 400 ) ) AS MOTIVO
        ,CAB.CODPARC AS CODCLI
        ,PM.PESOBRUTO AS TOTPESO
        ,CAB.NUNOTA AS NUMPED
        ,PM.AD_MAXIMA_PEDIDO AS NUMPEDRCA
        ,CAB.CODEMP AS CODFILIAL
        ,CAB.CODVEND AS CODUSUR
        ,CAB.VLRNOTA AS VLTOTAL
        ,CAB.DTNEG AS DATA
        ,CAB.OBSERVACAO AS OBS1
        ,CAB.CODPARCTRANSP AS CODFORNECFRETE
        ,CAB.OBSERVACAO AS OBS
        ,CAB.CODTIPVENDA AS CODPLPAG
        ,PM.AD_MAXIMA_NUMCAR AS NUMCAR
        ,PM.AD_MAXIMA_IDPEDIDO AS ID_PEDIDO
        ,CAB.CODTIPOPER
        ,CAB.DHTIPOPER
        , NULL AS NUNOTA_NOTA
        , CASE 
            WHEN CAB.CODCONTATOENTREGA IS NOT NULL OR CAB.CODCONTATO IS NOT NULL THEN 
                  LPAD( NVL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ), 10, 0 ) || LPAD( CAB.CODPARC , 10, 0 )
            ELSE
                  NULL
            END
         AS CODENDENTCLI      
     FROM AD_PEDIDO_MAXIMA PM
        ,TGFCAB_EXC CAB
        ,(SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM AD_MAXCONF) CONF
        ,TGFTOP TOP
    WHERE CAB.TIPMOV = 'P'
      AND CAB.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_HIST_VENDAS
      AND CAB.NUNOTA = PM.NUNOTA
      AND CAB.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
      AND TOP.CODTIPOPER = CAB.CODTIPOPER
      AND TOP.DHALTER = CAB.DHTIPOPER
      AND TOP.AD_ENVIARMAXIMA = 'S'
   UNION   --PEDIDOS CANCELADOS COM ORIGEM NO ERP 
   SELECT CAB.NUNOTA
        ,CAB.ORDEMCARGA
        ,'C' AS PENDENTE --CANCELADO
        ,CAB.STATUSNOTA
        ,CAST( CAB.OBSERVACAO AS VARCHAR( 400 ) ) AS MOTIVO
        ,CAB.CODPARC AS CODCLI
        ,NULL AS TOTPESO
        ,CAB.NUNOTA AS NUMPED
        ,NULL AS NUMPEDRCA
        ,CAB.CODEMP AS CODFILIAL
        ,CAB.CODVEND AS CODUSUR
        ,CAB.VLRNOTA AS VLTOTAL
        ,CAB.DTNEG AS DATA
        ,CAB.OBSERVACAO AS OBS1
        ,CAB.CODPARCTRANSP AS CODFORNECFRETE
        ,CAB.OBSERVACAO AS OBS
        ,CAB.CODTIPVENDA AS CODPLPAG
        ,NULL AS NUMCAR
        ,NULL AS ID_PEDIDO
        ,CAB.CODTIPOPER
        ,CAB.DHTIPOPER
        , NULL AS NUNOTA_NOTA
        , CASE 
            WHEN CAB.CODCONTATOENTREGA IS NOT NULL OR CAB.CODCONTATO IS NOT NULL THEN 
                  LPAD( NVL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ), 10, 0 ) || LPAD( CAB.CODPARC , 10, 0 )
            ELSE
                  NULL
            END
         AS CODENDENTCLI      
     FROM TGFCAB_EXC CAB
        ,(SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM AD_MAXCONF) CONF
        ,TGFTOP TOP
    WHERE CAB.TIPMOV = 'P'
      AND CAB.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_HIST_VENDAS
      AND CAB.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
      AND TOP.CODTIPOPER = CAB.CODTIPOPER
      AND TOP.DHALTER = CAB.DHTIPOPER
      AND TOP.AD_ENVIARMAXIMA = 'S'      
      AND NOT EXISTS ( SELECT 1 FROM AD_PEDIDO_MAXIMA PM WHERE PM.NUNOTA = CAB.NUNOTA )
/

/*
NomeObjeto: VW_MAXIMA_HISTORICO_PD_CAPAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_HISTORICO_PD_CAPAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_HISTORICO_PD_CAPAS AS
   SELECT *
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 20 )
                     AS MD5
                , SNK_GET_MD5(
                               T.POSICAO || T.NUMNOTA || TO_CHAR( T.DTFAT
                                                                ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.NUMTRANSVENDA
                               || T.NUNOTA || T.NUNOTA_NOTA || T.BLOQUEIO ||
                               T.ORDEMCARGA || T.PENDENTE || T.STATUSNOTA ||
                               T.MOTIVO || T.CODCLI || T.TOTPESO || T.
                               ORIGEMPED || T.VLTABELA || T.NUMPED || T.
                               NUMPEDRCA || T.CONDVENDA || T.CODFILIAL || T.
                               CODUSUR || T.VLATEND || T.CODCOB || T.VLTOTAL
                               || TO_CHAR( T.DATA, 'YYYY-MM-DD HH24:MI:SS' )
                               || T.OBS1 || T.CODFORNECFRETE || T.OBS || T.
                               CODPLPAG || T.TOTVOLUME || T.CODPRACA || T.
                               CODEMITENTE || T.NUMCAR || T.STATUSNFE || T.CODENDENTCLI )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( PD.NUNOTA ) AS CHAVE
                        , CASE
                             WHEN ( SELECT COUNT( 1 )
                                     FROM TSILIB LIB
                                    WHERE LIB.NUCHAVE = PD.NUNOTA
                                      AND LIB.TABELA IN ('TGFCAB', 'TGFITE')
                                      AND ( LIB.DHLIB IS NULL
                                        OR LIB.VLRLIBERADO < LIB.VLRATUAL ) ) >
                                     0 THEN
                                'B' /* BLOQUEADO */ 
                             WHEN NOTA.STATUSNFE IN ('A', 'S') THEN
                                'F' /* FATURADO */ 
                             WHEN NOTA.STATUSNFE = 'D' THEN
                                'C' /* DENEGADA */ 
                             WHEN NOTA.STATUSNFE NOT IN ('A', 'S') THEN
                                'P' /* PROCESSADO */ 
                             WHEN PD.PENDENTE = 'C' THEN --CANCELADO
                                'C' /* CANCELADO */ 
                             WHEN NVL( PD.ORDEMCARGA, 0 ) <> 0 THEN
                                'M' /* CARGA MONTADA */ 
                             WHEN PD.STATUSNOTA = 'L' THEN
                                'L' /* LIBERADO */ 
                             ELSE
                                'P' /* PENDENTE */ 
                          END
                             AS POSICAO
                        , ( SELECT OPCAO
                             FROM TDDOPC OPC
                            WHERE OPC.NUCAMPO =
                                     (SELECT NUCAMPO
                                        FROM TDDCAM
                                       WHERE NOMETAB = 'TGFCAB'
                                         AND NOMECAMPO = 'STATUSNFE')
                              AND OPC.VALOR = NOTA.STATUSNFE )
                             AS DESCRICAO_NFE
                        , NOTA.NUMNOTA AS NUMNOTA
                        , NOTA.DTFATUR AS DTFAT
                        , NOTA.DTFATUR AS DTSAIDA
                        , NOTA.HRENTSAI AS DTENTREGA
                        , NOTA.NUNOTA AS NUMTRANSVENDA
                        , NVL( NOTA.STATUSNFE, ' ' ) AS STATUSNFE
                        , PD.*
                        , NVL( TPO.AD_MAXIMA_TIPOVENDA, 0 ) AS CONDVENDA
                        , CASE
                             WHEN ( SELECT COUNT( 1 )
                                     FROM TSILIB LIB
                                    WHERE LIB.NUCHAVE = PD.NUNOTA
                                      AND LIB.TABELA IN ('TGFCAB', 'TGFITE')
                                      AND ( LIB.DHLIB IS NULL
                                        OR LIB.VLRLIBERADO < LIB.VLRATUAL ) ) >
                                     0 THEN
                                'S'
                             ELSE
                                'N'
                          END
                             AS BLOQUEIO
                        , NVL( TPO.AD_MAXIMAORIGEMPD, 'W' ) AS ORIGEMPED
                        , NVL( ( SELECT SUM( NVL( I.VLRCUS * I.QTDNEG, 0 ) )
                                  FROM TGFITE I
                                 WHERE I.NUNOTA = PD.NUNOTA
                                   AND USOPROD <> 'D' )
                             , 0 )
                             AS VLTABELA
                        , NVL(
                               ( SELECT SUM(
                                             CASE
                                                WHEN I.QTDNEG = 0 THEN
                                                   0
                                                ELSE
                                                   ( ( ( I.VLRTOT - I.VLRDESC
                                                    ) / I.QTDNEG ) * I.
                                                    QTDENTREGUE )
                                             END )
                                           AS VLR_ATENDIDO
                                  FROM TGFITE I
                                 WHERE I.NUNOTA = PD.NUNOTA )
                             , 0 )
                             AS VLATEND
                        , NVL( ( SELECT MIN( F.CODTIPTIT )
                                  FROM TGFFIN F, TGFTIT T
                                 WHERE F.NUNOTA = PD.NUNOTA
                                   AND T.CODTIPTIT = F.CODTIPTIT
                                   AND T.AD_MAXIMA = 'S' )
                             , 0 )
                             AS CODCOB
                        , NVL(
                               ( SELECT SUM( NVL( VOA.M3, NVL( PRO.M3, 0 ) )
                                            * ITE.QTDNEG )
                                           AS TOT_M3
                                  FROM TGFITE ITE
                                       LEFT JOIN TGFVOA VOA
                                          ON VOA.CODPROD = ITE.CODPROD
                                         AND VOA.CODVOL = ITE.CODVOL
                                     , TGFPRO PRO
                                 WHERE PRO.CODPROD = ITE.CODPROD
                                   AND ITE.NUNOTA = PD.NUNOTA
                                   AND ITE.USOPROD <> 'D' )
                             , 0 )
                             AS TOTVOLUME
                        , NVL(
                               ( SELECT CODTAB
                                  FROM TGFTAB
                                 WHERE NUTAB = (SELECT MAX( NUTAB )
                                                  FROM TGFITE I
                                                 WHERE I.NUNOTA = PD.NUNOTA) )
                             , 0 )
                             AS CODPRACA
                        , CASE
                             WHEN PD.NUMPEDRCA IS NOT NULL THEN 8888
                             ELSE NULL
                          END
                             AS CODEMITENTE
                     FROM VW_PEDIDOS_MAXIMA PD
                          LEFT JOIN TGFCAB NOTA
                             ON NOTA.NUNOTA = PD.NUNOTA_NOTA
                            AND NOTA.TIPMOV = 'V'
                        , TGFTOP TPO
                    WHERE TPO.CODTIPOPER = PD.CODTIPOPER
                      AND TPO.DHALTER = PD.DHTIPOPER) T) T2

/

/*
NomeObjeto: VW_MAXIMA_ESTOQUE
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ESTOQUE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ESTOQUE AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 6 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODFILIAL || T.CODPROD || T.QTBLOQUEADA ||
                               T.VLSTULTENT || T.CUSTOREP || T.CUSTOREAL ||
                               T.CUSTOFIN || T.QTPENDENTE || T.QTESTGER || T
                               .QTRESERV || TO_CHAR( T.DTULTENT
                                                   ,'YYYY-MM-DD HH24:MI:SS' ) )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( T.CODEMP, 5, 0 ) || LPAD( T.CODPROD
                                   , 10, 0 ) )
                             AS CHAVE
                        , T.CODEMP AS CODFILIAL
                        , T.CODPROD
                        , 0 AS QTBLOQUEADA
                        , 0.01 AS VLSTULTENT
                        , CASE
                             WHEN MAX( T.CUSGER ) = 0 THEN 0.01
                             ELSE MAX( T.CUSGER )
                          END
                             AS CUSTOREP
                        , CASE
                             WHEN MAX( T.CUSGER ) = 0 THEN 0.01
                             ELSE MAX( T.CUSGER )
                          END
                             AS CUSTOREAL
                        , CASE
                             WHEN MAX( T.CUSGER ) = 0 THEN 0.01
                             ELSE MAX( T.CUSGER )
                          END
                             AS CUSTOFIN
                        , 0 AS QTPENDENTE
                        , NVL( DTENTRADA, TRUNC( SYSDATE ) ) AS DTULTENT
                        , ( SUM( T.ESTOQUE ) - SUM( NVL( T.WMSBLOQUEADO, 0 )
                           ) )
                             AS QTESTGER
                        , SUM( NVL( T.RESERVADO, 0 ) ) AS QTRESERV
                     FROM (SELECT EST.CODEMP
                                ,EST.CODPROD
                                ,SUM( EST.RESERVADO ) AS RESERVADO
                                ,SUM( EST.ESTOQUE ) AS ESTOQUE
                                ,MAX( EST.DTENTRADA ) AS DTENTRADA
                                ,SUM( EST.WMSBLOQUEADO ) AS WMSBLOQUEADO
                                ,AVG(
                           NVL(
                           (             SELECT MAX( CUSGER ) AS CUSGER
                                           FROM TGFCUS CUS
                                          WHERE CUS.CODEMP = EST.CODEMP
                                            AND CUS.CODPROD = EST.CODPROD
                                            AND DTATUAL =
                              (                 SELECT MAX( DTATUAL )
                                                  FROM TGFCUS CUS2
                                                 WHERE CUS2.CODPROD =
                              EST.CODPROD
                                                   AND CUS2.CODEMP =
                              EST.CODEMP ) )
                                       ,0 ) )
                              AS CUSGER
                             FROM TGFEST EST
                            WHERE EST.TIPO = 'P'
                              AND EST.CODPARC = 0
                              AND EXISTS
                              (   SELECT 1
                                    FROM TSIEMP E
                                   WHERE E.CODEMP = EST.CODEMP
                                     AND E.AD_MAXIMA = 'S')
                              AND EXISTS
                              (   SELECT 1
                                    FROM TGFPRO P
                                   WHERE P.CODPROD = EST.CODPROD
                                     AND P.AD_MAXIMA = 'S')
                              AND EXISTS
                              (   SELECT 1
                                    FROM TGFLOC L
                                   WHERE L.CODLOCAL = EST.CODLOCAL
                                     AND L.AD_MAXIMA = 'S')
                           GROUP BY EST.CODEMP, EST.CODPROD
                           UNION
                           SELECT EMP.CODEMP
                                ,PRO.CODPROD
                                ,0 AS RESERVADO
                                ,0 AS ESTOQUE
                                ,SYSDATE AS DTENTRADA
                                ,0 AS WMSBLOQUEADO
                                ,0 CUSGER
                             FROM TGFPRO PRO, TSIEMP EMP
                            WHERE PRO.AD_MAXIMA = 'S'
                              AND EMP.AD_MAXIMA = 'S'
                              AND NOT EXISTS
                              (   SELECT 1
                                    FROM TGFEST EST
                                   WHERE EST.CODPROD = PRO.CODPROD
                                     AND EST.CODEMP = EMP.CODEMP
                                     AND EXISTS
                              (          SELECT 1
                                           FROM TGFLOC L
                                          WHERE L.CODLOCAL = EST.CODLOCAL
                                            AND L.AD_MAXIMA = 'S'))) T
                   GROUP BY T.CODEMP
                          , T.CODPROD
                          , NVL( DTENTRADA, TRUNC( SYSDATE ) )) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CLIENTE
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CLIENTE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CLIENTE AS
   SELECT *
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 3 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCLI || T.CODPLPAG || T.CODCOB || T.FANTASIA 
                               || T.CLIENTE || T.ATIVO || T.BLOQUEIOSEFAZ || T.CAIXAPOSTAL 
                               || T.CALCULAST || T.CEPENT || T.CGCENT 
                               || TO_CHAR(T.DTULTCOMP,'YYYY-MM-DD HH24:MI:SS' )
                               || T.CODCLIPRINC || T.CODUSU || T.COMPLEMENTOENT || T.CLASSIFICMS
                               || T.EMAIL || T.EMAILNFE || T.FAXCLI || T.INSCESTADNAUF 
                               || T.IMENT || T.ISENTOIPI || T.NUMEROENT 
                               || T.OBS || T.RG || T.TELENT || T.TIPOFJ 
                               || T.RAZAOSOCIAL || T.BAIRROENT || T.CODCIDADE 
                               || T.ESTENT || T.ENDERENT || T.MUNICENT || T.LATITUDE 
                               || T.LONGITUDE || T.PERCDESC || T.SIMPLESNACIONAL
                               || T.CODTAB || T.CODUSUR1 || T.CODUSUR2 
                               || T.VALIDARMULTIPLOVENDA || T.CONDVENDA5 
                               || T.CONDVENDA14 || T.BLOQUEIODEFINITIVO || T.BLOQUEIO 
                               || T.CODFILIALNF || T.CONSUMIDORFINAL
                               || T.IEENT || T.CLIENTEFONTEST || T.CONTRIBUINTE )
                     AS MD5LINHA
                , T.*
             FROM (SELECT T.*
                        , CASE
                             WHEN NVL( SUGTIPNEGSAID, 0 ) <> 0 THEN
                                SUGTIPNEGSAID
                             ELSE
                                ( SELECT MIN( CODTIPVENDA )
                                   FROM TGFTPV TPV
                                  WHERE TPV.DHALTER =
                                           ( SELECT MAX( V.DHALTER )
                                              FROM TGFTPV V
                                             WHERE V.CODTIPVENDA =
                                                      TPV.CODTIPVENDA )
                                    AND TPV.ATIVO = 'S'
                                    AND TPV.AD_MAXIMA = 'S'
                                    AND TPV.CODTIPVENDA <> 0
                                    AND TPV.SUBTIPOVENDA = 1 )
                          END
                             AS CODPLPAG
                     FROM (SELECT CAST( PAR.CODPARC AS VARCHAR( 10 ) )
                                     AS CHAVE
                                , PAR.CODPARC AS CODCLI
                                , PAR.CODREG AS CODROTA
                                , AD_TROCABONIFICADA AS CONDVENDA11
                                , ( SELECT SUGTIPNEGSAID AS CODTIPVENDA
                                     FROM TGFCPL CPL
                                    WHERE CPL.CODPARC = PAR.CODPARC )
                                     AS SUGTIPNEGSAID
                                , NVL( ( SELECT INTEIRO
                                          FROM TSIPAR
                                         WHERE CHAVE = 'TITTITPADRAOMAX' )
                                     , ( SELECT INTEIRO
                                          FROM TSIPAR
                                         WHERE CHAVE = 'TIPTITDINHEIRO' ) )
                                     AS CODCOB
                                , PAR.NOMEPARC AS FANTASIA
                                , CASE
                                     WHEN PAR.ATIVO = 'S' THEN 'N'
                                     ELSE 'S'
                                  END
                                     AS ATIVO
                                , PAR.SITCADSEFAZ AS BLOQUEIOSEFAZ
                                , PAR.CAIXAPOSTAL
                                , CASE
                                     WHEN PAR.DESCSTIVA = 'S' THEN 'S'
                                     ELSE 'N'
                                  END
                                     AS CALCULAST
                                , NVL( PAR.CGC_CPF, 0 ) AS CGCENT
                                , ( SELECT MAX(DTNEG) FROM TGFCAB C WHERE C.CODPARC = PAR.CODPARC AND C.TIPMOV = 'V' AND C.STATUSNOTA = 'L' ) AS DTULTCOMP
                                , PAR.CODPARCMATRIZ AS CODCLIPRINC
                                , PAR.CODUSU
                                , PAR.CLASSIFICMS
                                , PAR.EMAIL
                                , PAR.EMAILNFE
                                , PAR.FAX AS FAXCLI
                                , PAR.INSCESTADNAUF
                                , PAR.INSCMUN AS IMENT
                                , CASE WHEN PAR.TEMIPI = 'S' THEN 'N' ELSE 'S' END AS ISENTOIPI
                                , SUBSTR( PAR.OBSERVACOES, 1, 900 ) AS OBS
                                , PAR.IDENTINSCESTAD AS RG
                                , PAR.TIPPESSOA AS TIPOFJ
                                , PAR.RAZAOSOCIAL
                                , PAR.CODCID AS CODCIDADE
                                , PAR.LATITUDE
                                , PAR.LONGITUDE
                                , NVL( PAR.DESCFIN, 0 ) AS PERCDESC
                                , PAR.SIMPLES AS SIMPLESNACIONAL
                                , CASE
                                     WHEN ( SELECT INTEIRO
                                             FROM TSIPAR
                                            WHERE CHAVE = 'TIPTABPRECOS' ) =
                                             2 THEN
                                        ( SELECT CODTAB
                                           FROM TSIREG R
                                          WHERE R.CODREG = PAR.CODREG )
                                     ELSE
                                        PAR.CODTAB
                                  END
                                     AS CODTAB
                                , NVL( PAR.CODVEND, 0 ) AS CODUSUR1
                                , CASE
                                     WHEN EXISTS
                                             (SELECT 1
                                                FROM AD_MAXCONF
                                               WHERE ENVIA_GERENTE = 'S') THEN
                                        9999
                                     ELSE
                                        0
                                  END
                                     AS CODUSUR2
                                , 'S' AS VALIDARMULTIPLOVENDA
                                , CASE
                                     WHEN ( SELECT COUNT( 1 ) AS QTD
                                             FROM TGFVEN
                                            WHERE CODPARC = PAR.CODPARC ) > 0 THEN
                                        'N'
                                     ELSE
                                        'S'
                                  END
                                     AS CONDVENDA5 --BONIFICACAO PRE-VENDA
                                , 'S' AS CONDVENDA14 --PRONTA ENTREGA NORMAL
                                , CASE
                                     WHEN ( SELECT COUNT( 1 ) AS QTD
                                             FROM TGFVEN
                                            WHERE CODPARC = PAR.CODPARC ) > 0 THEN
                                        'N'
                                     ELSE
                                        'S'
                                  END
                                     AS CONDVENDA24 --BONIFICACAO PRONTA ENTREGA
                                , CASE
                                     WHEN PAR.ATIVO = 'S' THEN 'N'
                                     ELSE 'S'
                                  END
                                     AS BLOQUEIODEFINITIVO
                                , PAR.BLOQUEAR AS BLOQUEIO
                                , PAR.CODEMPPREF AS CODFILIALNF
                                , 1 AS CODFUNCULTALTER
                                , CASE
                                     WHEN NVL( PAR.CLASSIFICMS, 'Z' ) IN
                                             ('C', 'X') THEN
                                        'S'
                                     ELSE
                                        'N'
                                  END
                                     AS CONSUMIDORFINAL
                                , CASE
                                     WHEN PAR.IDENTINSCESTAD IS NULL THEN
                                        'ISENTO'
                                     ELSE
                                        PAR.IDENTINSCESTAD
                                  END
                                     AS IEENT
                                , CASE
                                     WHEN ( SELECT INTEIRO
                                             FROM TSIPAR
                                            WHERE CHAVE = 'TIPTABPRECOS' ) =
                                             2 THEN
                                        ( SELECT CODTAB
                                           FROM TSIREG R
                                          WHERE R.CODREG = PAR.CODREG )
                                     ELSE
                                        PAR.CODTAB
                                  END
                                     AS CODPRACA
                                , NVL( PAR.RAZAOSOCIAL, PAR.NOMEPARC )
                                     AS CLIENTE
                                , ( SELECT CASE
                                              WHEN MAX( M.GRUPOICMS ) IS NULL THEN
                                                 'N'
                                              ELSE
                                                 'S'
                                           END
                                     FROM TGFPAEM M
                                    WHERE M.CODPARC = PAR.CODPARC )
                                     AS CLIENTEFONTEST
                                /*ATENÇÃO, os campos referentes a endereço Comercial e Entrega na máxima são invertidos*/  
                                , CASE NVL(ENDE.CODEND, 0) WHEN 0 THEN NULL ELSE ENDE.NOMEEND END AS ENDERENT                               
                                , CASE NVL(CID.CODCID, 0)  WHEN 0 THEN NULL ELSE CID.NOMECID  END AS MUNICENT
                                , CASE NVL(BAIRRO.CODBAI, 0)  WHEN 0 THEN NULL ELSE BAIRRO.NOMEBAI  END AS BAIRROENT
                                , CASE NVL(UFS.UF, '0')      WHEN '0' THEN NULL ELSE UFS.UF       END AS ESTENT
                                , PAR.NUMEND AS NUMEROENT
                                , PAR.CEP AS CEPENT
                                , PAR.COMPLEMENTO AS COMPLEMENTOENT
                                , NVL( PAR.TELEFONE, 0 ) AS TELENT
                                , CASE NVL(CPL_END.CODEND, 0) WHEN 0   THEN NULL ELSE CPL_END.NOMEEND END AS ENDERCOM                               
                                , CASE NVL(CPL_CID.CODCID, 0) WHEN 0   THEN NULL ELSE CPL_CID.NOMECID END AS MUNICCOM
                                , CASE NVL(CPL_BAI.CODBAI, 0) WHEN 0   THEN NULL ELSE CPL_BAI.NOMEBAI END AS BAIRROCOM
                                , CASE NVL(CPL_UFS.UF, '0')   WHEN '0' THEN NULL ELSE CPL_UFS.UF      END AS ESTCOM
                                , CPL.COMPLENTREGA AS COMPLEMENTOCOM
                                , CPL.NUMENTREGA AS NUMEROCOM
                                , CPL.CEPENTREGA AS CEPCOM
                                , NVL(CPL.AD_MAXIMA_TELENTREGA, 0) AS TELCOM
                                , CASE WHEN PAR.CLASSIFICMS = 'C' THEN 'N' ELSE 'S' END AS CONTRIBUINTE
                             FROM TGFPAR PAR
                                  LEFT JOIN TSIBAI BAIRRO
                                     ON BAIRRO.CODBAI = PAR.CODBAI
                                  LEFT JOIN TSICID CID
                                     ON CID.CODCID = PAR.CODCID
                                  LEFT JOIN TSIUFS UFS ON UFS.CODUF = CID.UF
                                  LEFT JOIN TSIEND ENDE
                                     ON ENDE.CODEND = PAR.CODEND
                                  LEFT JOIN TGFCPL CPL
                                     ON CPL.CODPARC = PAR.CODPARC
                                  LEFT JOIN TSIEND CPL_END
                                     ON CPL.CODENDENTREGA = CPL_END.CODEND
                                  LEFT JOIN TSICID CPL_CID
                                     ON CPL.CODCIDENTREGA = CPL_CID.CODCID
                                  LEFT JOIN TSIBAI CPL_BAI
                                     ON CPL_BAI.CODBAI = CPL.CODBAIENTREGA
                                  LEFT JOIN TSIUFS CPL_UFS
                                     ON CPL_UFS.CODUF = CPL_CID.UF
                            WHERE PAR.AD_MAXIMA_CLIENTE = 'S'
                              AND PAR.CLIENTE = 'S') T) T) T2
/

/*
NomeObjeto: VW_MAXIMA_FORNECEDOR
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FORNECEDOR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FORNECEDOR AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 18 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CGC_CPF || T.ATIVO || T.NOMECID || T.CODPARC
                               || T.UF || T.NOMEPARC || T.RAZAOSOCIAL || T.
                               ENDER || T.BAIRRO || T.TELFAB || T.REVENDA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT PAR.CODPARC AS CHAVE
                        , PAR.CGC_CPF
                        , PAR.ATIVO
                        , CID.NOMECID
                        , PAR.CODPARC
                        , UFS.UF
                        , PAR.NOMEPARC
                        , PAR.RAZAOSOCIAL
                        , ENDE.NOMEEND AS ENDER
                        , BAIRRO.NOMEBAI AS BAIRRO
                        , PAR.TELEFONE AS TELFAB
                        , 'S' AS REVENDA
                     FROM TGFPAR PAR
                          LEFT JOIN TSIBAI BAIRRO
                             ON BAIRRO.CODBAI = PAR.CODBAI
                          LEFT JOIN TSICID CID ON CID.CODCID = PAR.CODCID
                          LEFT JOIN TSIUFS UFS ON UFS.CODUF = CID.UF
                          LEFT JOIN TSIEND ENDE ON ENDE.CODEND = PAR.CODEND
                    WHERE PAR.AD_MAXIMA_FORNECEDOR = 'S'
                      AND PAR.FORNECEDOR = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_DEPARTAMENTO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_DEPARTAMENTO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_DEPARTAMENTO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 5 )
                     AS MD5
                , SNK_GET_MD5( T.CODEPTO || T.DESCRICAO ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( GRU.CODGRUPOPROD ) AS CHAVE
                        , GRU.CODGRUPOPROD AS CODEPTO
                        , GRU.DESCRGRUPOPROD AS DESCRICAO
                     FROM TGFGRU GRU
                    WHERE GRU.AD_MAXIMA = 'S'
                      AND GRU.GRAU = 1) T) T2
/

/*
NomeObjeto: VW_MAXIMA_SECAO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SECAO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SECAO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 56 )
                     AS MD5
                , SNK_GET_MD5( T.CODSEC || T.DESCRICAO || T.CODEPTO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( GRU.CODGRUPOPROD ) AS CHAVE
                        , GRU.CODGRUPOPROD AS CODSEC
                        , GRU.DESCRGRUPOPROD AS DESCRICAO
                        , GRU.CODGRUPAI AS CODEPTO
                     FROM TGFGRU GRU
                    WHERE GRU.AD_MAXIMA = 'S'
                      AND GRU.GRAU = 2) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CATEGORIA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CATEGORIA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CATEGORIA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 57 )
                     AS MD5
                , SNK_GET_MD5( T.CODCATEGORIA || T.CATEGORIA || T.CODSEC )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( GRU.CODGRUPOPROD ) AS CHAVE
                        , GRU.CODGRUPOPROD AS CODCATEGORIA
                        , GRU.DESCRGRUPOPROD AS CATEGORIA
                        , GRU.CODGRUPAI AS CODSEC
                     FROM TGFGRU GRU
                    WHERE GRU.AD_MAXIMA = 'S'
                      AND GRU.GRAU = 3) T) T2
/

/*
NomeObjeto: VW_MAXIMA_SUBCATEGORIA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SUBCATEGORIA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SUBCATEGORIA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 58 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODSUBCATEGORIA || T.SUBCATEGORIA || T.
                               CODCATEGORIA || T.CODSEC )
                     AS MD5LINHA
                , T.*
             FROM (SELECT DISTINCT TO_CHAR( GRU.CODGRUPOPROD ) AS CHAVE
                                 , GRU.CODGRUPOPROD AS CODSUBCATEGORIA
                                 , GRU.DESCRGRUPOPROD AS SUBCATEGORIA
                                 , GRU.CODGRUPAI AS CODCATEGORIA
                                 , ( SELECT G.CODGRUPAI
                                      FROM TGFGRU G
                                     WHERE G.CODGRUPOPROD = GRU.CODGRUPAI )
                                      AS CODSEC
                     FROM TGFGRU GRU
                    WHERE GRU.AD_MAXIMA = 'S'
                      AND GRU.GRAU = 4) T) T2
/

/*
NomeObjeto: VW_MAXIMA_PRODUTOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRODUTOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRODUTOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 4 )
                     AS MD5
                , SNK_GET_MD5(
                               T.SUBCATEGORIA || T.CATEGORIA || T.SECAO || T
                               .DEPARTAMENTO || T.CODPROD || T.DESCRPROD ||
                               T.CODMARCA || T.MARCA || T.USOPROD || T.
                               REFERENCIA || T.ALTURA || T.CODCAT || T.
                               CODPARCFORN || T.CODPAT || T.ENDIMAGEM || T.
                               ORIGPROD || T.PERMCOMPPROD || T.PESOBRUTO ||
                               T.PESOLIQ || T.QTDEMB || T.USACONTPESOVAR ||
                               T.REVENDA || T.CLASSIFICFISCAL || T.EMBALAGEM
                               || T.EMBALAGEMMASTER || T.UNIDADE || T.
                               UNIDADEMASTER || T.QTUNIT || T.QTUNITCX || T.
                               MULTIPLO || T.VOLUME || T.RESTRICAOTRANSP ||
                               TO_CHAR
                               ( T.DTCADASTRO, 'YYYY-MM-DD HH24:MI:SS' ) ||
                               T.DESCRICAO2 || T.CODPRODPRINC || T.PERCIPIVENDA || T.CODGRUPOTRIBUT
                               )
                     AS MD5LINHA
                , T.*
             FROM (SELECT CASE
                             WHEN NIVEL04 <> MASCARA_GRUPO
                              AND NIVEL04 <> T.CATEGORIA
                              AND NIVEL04 <> T.SECAO
                              AND NIVEL04 <> T.DEPARTAMENTO THEN
                                NIVEL04
                             ELSE
                                0
                          END
                             AS SUBCATEGORIA
                        , T.*
                     FROM (SELECT CASE
                                     WHEN NIVEL03 <> MASCARA_GRUPO
                                      AND NIVEL03 <> T.SECAO
                                      AND NIVEL03 <> T.DEPARTAMENTO THEN
                                        NIVEL03
                                     ELSE
                                        CASE
                                           WHEN NIVEL04 <> MASCARA_GRUPO
                                            AND NIVEL04 <> T.SECAO
                                            AND NIVEL04 <> T.DEPARTAMENTO THEN
                                              NIVEL04
                                           ELSE
                                              0
                                        END
                                  END
                                     AS CATEGORIA
                                , T.*
                             FROM (SELECT CASE
                                             WHEN NIVEL02 <> MASCARA_GRUPO
                                              AND NIVEL02 <> T.DEPARTAMENTO THEN
                                                NIVEL02
                                             ELSE
                                                CASE
                                                   WHEN NIVEL03 <>
                                                           MASCARA_GRUPO
                                                    AND NIVEL03 <>
                                                           T.DEPARTAMENTO THEN
                                                      NIVEL03
                                                   ELSE
                                                      CASE
                                                         WHEN NIVEL04 <>
                                                                 MASCARA_GRUPO
                                                          AND NIVEL04 <>
                                                                 T.DEPARTAMENTO THEN
                                                            NIVEL04
                                                         ELSE
                                                            0
                                                      END
                                                END
                                          END
                                             AS SECAO
                                        , T.*
                                     FROM (SELECT CASE
                                                     WHEN NIVEL01 <>
                                                             MASCARA_GRUPO THEN
                                                        NIVEL01
                                                     ELSE
                                                        CASE
                                                           WHEN NIVEL02 <>
                                                                   MASCARA_GRUPO THEN
                                                              NIVEL02
                                                           ELSE
                                                              CASE
                                                                 WHEN NIVEL03 <>
                                                                         MASCARA_GRUPO THEN
                                                                    NIVEL03
                                                                 ELSE
                                                                    CASE
                                                                       WHEN NIVEL04 <>
                                                                               MASCARA_GRUPO THEN
                                                                          NIVEL04
                                                                       ELSE
                                                                          0
                                                                    END
                                                              END
                                                        END
                                                  END
                                                     AS DEPARTAMENTO
                                                , T.*
                                             FROM (SELECT TO_CHAR(
                                                                   PRO.CODPROD )
                                                             AS CHAVE
                                                        , PRO.CODPROD
                                                        , PRO.DESCRPROD
                                                        , NVL(
                                                               ( SELECT GRU.CODGRUPAI
                                                                  FROM TGFGRU GRU
                                                                 WHERE GRU.CODGRUPOPROD =
                                                                          ( SELECT GRU.CODGRUPAI
                                                                             FROM TGFGRU GRU
                                                                            WHERE GRU.CODGRUPOPROD =
                                                                                     ( SELECT GRU.CODGRUPAI
                                                                                        FROM TGFGRU GRU
                                                                                       WHERE GRU.CODGRUPOPROD =
                                                                                                PRO.CODGRUPOPROD ) ) )
                                                             , MASK.MASCARA_GRUPO )
                                                             AS NIVEL01
                                                        , NVL(
                                                               ( SELECT GRU.CODGRUPAI
                                                                  FROM TGFGRU GRU
                                                                 WHERE GRU.CODGRUPOPROD =
                                                                          ( SELECT GRU.CODGRUPAI
                                                                             FROM TGFGRU GRU
                                                                            WHERE GRU.CODGRUPOPROD =
                                                                                     PRO.CODGRUPOPROD ) )
                                                             , MASK.MASCARA_GRUPO )
                                                             AS NIVEL02
                                                        , NVL(
                                                               ( SELECT GRU.CODGRUPAI
                                                                  FROM TGFGRU GRU
                                                                 WHERE GRU.CODGRUPOPROD =
                                                                          PRO.CODGRUPOPROD )
                                                             , MASK.MASCARA_GRUPO )
                                                             AS NIVEL03
                                                        , NVL(
                                                               PRO.CODGRUPOPROD
                                                             , MASK.MASCARA_GRUPO )
                                                             AS NIVEL04
                                                        , NVL( PRO.CODMARCA
                                                             , 0 )
                                                             AS CODMARCA
                                                        , PRO.MARCA
                                                        , PRO.USOPROD
                                                        , NVL( PRO.REFERENCIA
                                                             , PRO.CODPROD )
                                                             AS REFERENCIA
                                                        , PRO.ALTURA
                                                        , PRO.CODCAT
                                                        , NVL(
                                                               PRO.CODPARCFORN
                                                             , 0 )
                                                             AS CODPARCFORN
                                                        , PRO.CODPAT
                                                        , PRO.ENDIMAGEM
                                                        , PRO.ORIGPROD
                                                        , PRO.PERMCOMPPROD
                                                        , NVL( PRO.PESOBRUTO
                                                             , 0 )
                                                             AS PESOBRUTO
                                                        , NVL( PRO.PESOLIQ
                                                             , 0 )
                                                             AS PESOLIQ
                                                        , NVL( PRO.QTDEMB
                                                             , 0 )
                                                             AS QTDEMB
                                                        , PRO.USACONTPESOVAR
                                                        , PRO.ATIVO
                                                             AS REVENDA
                                                        , PRO.NCM
                                                             AS CLASSIFICFISCAL
                                                        , ( SELECT VOL.DESCRVOL
                                                             FROM TGFVOL VOL
                                                            WHERE VOL.CODVOL =
                                                                     PRO.CODVOL )
                                                             AS EMBALAGEM
                                                        , ( SELECT VOL.DESCRVOL
                                                             FROM TGFVOL VOL
                                                            WHERE VOL.CODVOL =
                                                                     PRO.CODVOLCOMPRA )
                                                             AS EMBALAGEMMASTER
                                                        , PRO.CODVOL
                                                             AS UNIDADE
                                                        , PRO.CODVOLCOMPRA
                                                             AS UNIDADEMASTER
                                                        , NVL(
                                                               ( SELECT VOA.QUANTIDADE
                                                                  FROM TGFVOA VOA
                                                                 WHERE VOA.CODPROD =
                                                                          PRO.CODPROD
                                                                   AND VOA.CODVOL =
                                                                          PRO.CODVOL )
                                                             , 1 )
                                                             AS QTUNIT
                                                        , NVL(
                                                               ( SELECT VOA.QUANTIDADE
                                                                  FROM TGFVOA VOA
                                                                 WHERE VOA.CODPROD =
                                                                          PRO.CODPROD
                                                                   AND VOA.CODVOL =
                                                                          PRO.CODVOLCOMPRA )
                                                             , 1 )
                                                             AS QTUNITCX
                                                        , PRO.AGRUPMIN
                                                             AS MULTIPLO
                                                        , PRO.M3 AS VOLUME
                                                        , PRO.AD_MAXIMA_TIPO
                                                             AS RESTRICAOTRANSP
                                                        , TRUNC( DTALTER )
                                                             AS DTCADASTRO
                                                        , PRO.COMPLDESC
                                                             AS DESCRICAO2
                                                        , PRO.CODPROD
                                                             AS CODPRODPRINC
                                                        , ( SELECT NVL(
                                                                        IPI.PERCENTUAL
                                                                      , 0 )
                                                             FROM TGFIPI IPI
                                                            WHERE IPI.CODIPI =
                                                                     PRO.CODIPI )
                                                             AS PERCIPIVENDA
                                                        , MASK.MASCARA_GRUPO
                                                        , NVL( PRO.GRUPOICMS, 0 ) AS CODGRUPOTRIBUT 
                                                     FROM TGFPRO PRO
                                                        , (SELECT -999999999
                                                                     AS MASCARA_GRUPO
                                                             FROM DUAL) MASK
                                                    WHERE PRO.AD_MAXIMA = 'S') T) T) T) T) T) T2
/

/*
NomeObjeto: VW_MAXIMA_TSICID
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TSICID
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TSICID AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 1 )
                     AS MD5
                , SNK_GET_MD5( T.CODCID || T.CODMUNFIS || T.NOMECID || T.UF )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CID.CODCID ) AS CHAVE
                        , CID.CODCID
                        , CID.CODMUNFIS
                        , CID.NOMECID
                        , UFS.UF
                     FROM TSICID CID
                          INNER JOIN TSIUFS UFS ON CID.UF = UFS.CODUF
                    WHERE CID.AD_MAXIMA = 'S'
                      AND CID.CODCID <> 0) T) T2
/

/*
NomeObjeto: VW_MAXIMA_TABELA_PRECO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TABELA_PRECO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TABELA_PRECO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 16 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODTAB || T.NUTAB || T.CODPROD || TO_CHAR(
                               T.DTVIGOR
                                                                          ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.CODREG || T.
                               VLRVENDA || T.CUSTO || T.TEMIPIVENDA || T.PERDESCMAX || T.PERACRESCMAX )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( TAB.CODTAB, 5, 0 ) || LPAD(
                                   PRO.CODPROD
                                                                   ,10
                                                                   ,0 ) )
                             AS CHAVE
                        , TAB.CODTAB
                        , TAB.NUTAB
                        , PRO.CODPROD
                        , TAB.DTVIGOR
                        , TAB.CODTAB AS CODREG
                        , SNK_GET_PRECO( TAB.NUTAB
                                       , PRO.CODPROD
                                       , TRUNC( SYSDATE ) )
                             AS VLRVENDA
                        , NVL(
                               ( SELECT MAX( CUSMED )
                                  FROM TGFCUS C
                                 WHERE C.CODPROD = PRO.CODPROD
                                   AND DTATUAL =
                                          ( SELECT MAX( DTATUAL )
                                             FROM TGFCUS C2
                                            WHERE C2.CODEMP = C.CODEMP
                                              AND C2.CODPROD = C.CODPROD
                                              AND C2.CODLOCAL = C.CODLOCAL
                                              AND C2.CONTROLE = C.CONTROLE
                                              AND C2.DTATUAL <=
                                                     TRUNC( SYSDATE ) ) )
                             , 0.01 )
                             AS CUSTO
                        , PRO.TEMIPIVENDA
                        , CASE WHEN CONF.USALIMITEFLEX = 'N'
                                    THEN NVL( PRO.DESCMAX, 0 ) 
                                    ELSE NVL(PRO.DESCMAXFLEX, 0) END AS PERDESCMAX
                        , CASE WHEN CONF.USALIMITEFLEX = 'N'
                                    THEN 0
                                    ELSE NVL(PRO.ACRESCMAX, 0) END AS PERACRESCMAX                                    
                     FROM TGFTAB TAB
                          INNER JOIN TGFPRO PRO ON PRO.AD_MAXIMA = 'S'
                          INNER JOIN TGFNTA NTA
                             ON NTA.CODTAB = TAB.CODTAB
                            AND NTA.AD_MAXIMA = 'S'
                          , (SELECT NVL(USALIMITEFLEX,'N') AS USALIMITEFLEX FROM AD_MAXCONF) CONF
                    WHERE TAB.NUTAB =
                             ( SELECT MAX( T.NUTAB )
                                FROM TGFTAB T
                               WHERE T.CODTAB = TAB.CODTAB
                                 AND T.DTVIGOR =
                                        ( SELECT MAX( T2.DTVIGOR )
                                           FROM TGFTAB T2
                                          WHERE T2.CODTAB = TAB.CODTAB
                                            AND T2.DTVIGOR <=
                                                   TRUNC( SYSDATE ) ) )) T) T2
/

/*
NomeObjeto: VW_MAXIMA_EMBALAGENS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_EMBALAGENS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_EMBALAGENS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 33 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODAUXILIAR || T.UNIDADE || T.CODPROD || T.
                               CODFILIAL || T.EMBALAGEM || T.QTUNIT || T.
                               FATORPRECO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                   LPAD            ( EMP.CODEMP, 5, 0 ) || LPAD( VOA.CODPROD
                   , 10, 0 ) || VOA.CODVOL )
                      AS CHAVE
                        ,VOA.CODBARRA AS CODAUXILIAR
                        ,VOA.CODVOL AS UNIDADE
                        ,VOA.CODPROD AS CODPROD
                        ,EMP.CODEMP AS CODFILIAL
                        ,VOL.DESCRVOL AS EMBALAGEM
                        ,CASE
                      WHEN VOA.DIVIDEMULTIPLICA = 'D' THEN
                      ROUND( 1 / VOA.QUANTIDADE, 6 )
                      ELSE
                      VOA.QUANTIDADE
                   END
                      AS QTUNIT
                        ,VOA.MULTIPVLR AS FATORPRECO
                        ,VOA.DIVIDEMULTIPLICA AS DIVIDEMULTIPLICA
                     FROM TGFVOA VOA, TGFVOL VOL, TSIEMP EMP
                    WHERE EMP.AD_MAXIMA = 'S'
                      AND VOA.AD_MAXIMA = 'S' 
                      AND VOA.CODVOL = VOL.CODVOL
                      AND VOA.CODBARRA IS NOT NULL
                      AND EXISTS
                      (   SELECT 1
                            FROM TGFPRO P
                           WHERE P.CODPROD = VOA.CODPROD
                             AND P.AD_MAXIMA = 'S')
                   UNION
                   SELECT LPAD( EMP.CODEMP, 5, 0 ) || LPAD( PRO.CODPROD
                                                          ,10
                                                          ,0 ) || PRO.CODVOL
                      AS CHAVE
                        ,PRO.REFERENCIA AS CODAUXILIAR
                        ,PRO.CODVOL AS UNIDADE
                        ,PRO.CODPROD AS CODPROD
                        ,EMP.CODEMP AS CODFILIAL
                        ,VOL.DESCRVOL AS EMBALAGEM
                        ,1 AS QTUNIT
                        ,1 AS FATORPRECO
                        ,'M' AS DIVIDEMULTIPLICA
                     FROM TGFPRO PRO, TGFVOL VOL, TSIEMP EMP
                    WHERE EMP.AD_MAXIMA = 'S'
                      AND PRO.AD_MAXIMA = 'S'
                      AND PRO.REFERENCIA IS NOT NULL
                      AND VOL.CODVOL = PRO.CODVOL) T) T2
/

/*
NomeObjeto: VW_MAX_CLIENTES_VENDEDOR
TipoObjeto: VIEW
NomeTabela: VW_MAX_CLIENTES_VENDEDOR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_CLIENTES_VENDEDOR AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 34 )
                     AS MD5
                , SNK_GET_MD5( T.CODCLI || T.CODUSUR ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CODVEND, 5, 0 ) || LPAD( CODPARC, 10
                                   , 0 ) )
                             AS CHAVE
                        , RPV.CODPARC AS CODCLI
                        , RPV.CODVEND AS CODUSUR
                     FROM TGFRPV RPV) T) T2
/

/*
NomeObjeto: VW_MAX_COBRANCAS_PAG
TipoObjeto: VIEW
NomeTabela: VW_MAX_COBRANCAS_PAG
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_COBRANCAS_PAG AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 35 )
                     AS MD5
                , SNK_GET_MD5( T.CODPLPAG || T.CODCOB ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( PPG.CODTIPVENDA, 5, 0 ) || LPAD(
                                   PPG.CODTIPTITPAD
                                                                        ,5
                                                                        ,0 ) )
                             AS CHAVE
                        , PPG.CODTIPVENDA AS CODPLPAG
                        , PPG.CODTIPTITPAD AS CODCOB
                     FROM TGFTPV TPV, TGFPPG PPG
                    WHERE TPV.CODTIPVENDA = PPG.CODTIPVENDA
                      AND TPV.DHALTER =
                             (SELECT MAX( DHALTER )
                                FROM TGFTPV T2
                               WHERE T2.CODTIPVENDA = TPV.CODTIPVENDA)
                      AND TPV.AD_MAXIMA = 'S'
                      AND EXISTS
                             (SELECT 1
                                FROM TGFTIT TIT
                               WHERE TIT.CODTIPTIT = PPG.CODTIPTITPAD
                                 AND TIT.AD_MAXIMA = 'S'
                                 AND TIT.CODTIPTIT <> 0)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_FLEX_SALDO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FLEX_SALDO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FLEX_SALDO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 15 )
                     AS MD5
                , SNK_GET_MD5( T.CODUSUR || T.SALDOCC || T.LIMCREDCC )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODVEND ) AS CHAVE
                        , CODVEND AS CODUSUR
                        , SALDODISP AS SALDOCC
                        , 0 AS LIMCREDCC
                     FROM TGFVEN
                    WHERE AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_BANCOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_BANCOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_BANCOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 53 )
                     AS MD5
                , SNK_GET_MD5( T.CODBANCO || T.NOME ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODBCO ) AS CHAVE
                        , CODBCO AS CODBANCO
                        , NOMEBCO AS NOME
                     FROM TSIBCO
                    WHERE AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_DOCELETRONICO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_DOCELETRONICO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_DOCELETRONICO AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 40 )
                     AS MD5
                , SNK_GET_MD5( T.NUMTRANSACAO || SUBSTR( T.XMLNFE, 1, 400 )
                              || T.NUMPEDRCA || T.NUMPED )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CAB.NUNOTA ) AS CHAVE
                        , CAB.NUNOTA AS NUMTRANSACAO
                        , NFE.XML AS XMLNFE
                        , CAB.AD_MAXIMA_PEDIDO AS NUMPEDRCA
                        , SNK_GET_PD_MAXIMA( CAB.NUNOTA ) AS NUMPED
                     FROM TGFNFE NFE
                          INNER JOIN TGFCAB CAB ON NFE.NUNOTA = CAB.NUNOTA
                        , (SELECT QTD_DIAS_NOTAS FROM AD_MAXCONF) CONF
                    WHERE CAB.TIPMOV = 'V'
                      AND CAB.STATUSNOTA = 'L'
                      AND CAB.STATUSNFE IN ('A', 'S')
                      AND CAB.DTNEG >=
                             (TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_ULTIMACOMPRA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ULTIMACOMPRA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ULTIMACOMPRA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 42 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCLI || TO_CHAR( T.DTULTCOMP
                                                  ,'YYYY-MM-DD HH24:MI:SS' ) )
                     AS MD5LINHA
                , T.*
             FROM (  SELECT TO_CHAR( CAB.CODPARC ) AS CHAVE
                        , CAB.CODPARC AS CODCLI
                        , MAX(CAB.DTNEG) AS DTULTCOMP
                     FROM TGFCAB CAB
                        , (SELECT QTD_DIAS_NOTAS FROM AD_MAXCONF) CONF
                    WHERE CAB.TIPMOV = 'V'
                      AND EXISTS
                             (SELECT 1
                                FROM TGFPAR PAR
                               WHERE PAR.CODPARC = CAB.CODPARC
                                 AND PAR.AD_MAXIMA_CLIENTE = 'S'
                                 AND PAR.CLIENTE = 'S')
                      AND CAB.STATUSNOTA = 'L'
                      AND CAB.DTNEG >=
                             (TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS)
                      GROUP BY CAB.CODPARC
                             ) T) T2
/

/*
NomeObjeto: VW_MAXIMA_REMESSA_REAL
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_REMESSA_REAL
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_REMESSA_REAL AS
   SELECT DISTINCT ITE.NUNOTA
     FROM TGFCAB CAB
        , TGFTOP TPO
        , TGFITE ITE
        , (SELECT C.MODELOREMESSA, C.QTD_DIAS_NOTAS
             FROM AD_MAXCONF C) CONF
    WHERE CAB.NUNOTA = ITE.NUNOTA
      AND CAB.TIPMOV = 'V'
      AND CAB.STATUSNOTA = 'L'
      AND CAB.STATUSNFE IN ('A', 'S')
      AND TPO.CODTIPOPER = CAB.CODTIPOPER
      AND TPO.DHALTER = CAB.DHTIPOPER
      AND TPO.AD_MAXIMA_TIPOVENDA = 13 /* ABASTECIMENTO ESTOQUE VEICULO PRONTA ENTREGA */  
      AND CAB.DTNEG >= (TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS)
      AND NOT EXISTS
             (SELECT 1
                FROM TGFVAR V, TGFCAB CR /* CAB REMESSA */  
                                        , TGFTOP TPO
               WHERE V.NUNOTAORIG = CAB.NUNOTA
                 AND V.NUNOTA = CR.NUNOTA
                 AND CR.CODVEND = CAB.CODVEND
                 AND TPO.CODTIPOPER = CR.CODTIPOPER
                 AND TPO.DHALTER = CR.DHTIPOPER
                 AND TPO.AD_MAXIMA_TIPOVENDA = 13 /* 13 = ESTOQUE VEICULO ( PRONTA ENTREGA ) */  
                 AND CR.TIPMOV = 'V'
                 AND CR.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS)
/

/*
NomeObjeto: VW_MAXIMA_RETORNO_VEICULO
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_RETORNO_VEICULO
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_RETORNO_VEICULO AS
   SELECT T.*, ROUND( T.QTDNEG * T.VLRUNIT, 2 ) AS VLRTOT
     FROM (SELECT EST.CODEMP
                , EST.CODPROD
                , NVL( EST.CODLOCAL, 0 ) AS CODLOCALORIG
                , EST.CONTROLE
                , PRO.USOPROD
                , EST.ESTOQUE AS QTDNEG
                , PRO.CODVOL
                , NVL(
                       SNK_GET_PRECO( TAB.NUTAB
                                    , PRO.CODPROD
                                    , TRUNC( SYSDATE ) )
                     , 0 )
                     AS VLRUNIT
                , VEN.CODVEND
             FROM TGFEST EST
                , TGFVEN VEN
                , TGFPRO PRO
                , (SELECT MODELORETORNO, LOCAL_TRANSITO
                     FROM AD_MAXCONF C) CONF
                , (SELECT MAX( T.NUTAB ) AS NUTAB
                     FROM TGFTAB T
                    WHERE T.CODTAB = 0
                      AND T.DTVIGOR = (SELECT MAX( DTVIGOR )
                                         FROM TGFTAB M
                                        WHERE M.CODTAB = 0
                                          AND M.DTVIGOR <= TRUNC( SYSDATE ))) TAB
            WHERE VEN.AD_MAXIMA_LOCAL = EST.CODLOCAL
              AND PRO.CODPROD = EST.CODPROD
              AND PRO.AD_MAXIMA = 'S'
              AND VEN.AD_MAXIMA = 'S'
              AND EST.ESTOQUE > 0
              AND EXISTS
                     (SELECT 1
                        FROM TSIEMP E
                       WHERE E.CODEMP = EST.CODEMP
                         AND E.AD_MAXIMA = 'S')
              AND EXISTS
                     (SELECT 1
                        FROM TGFLOC L
                       WHERE L.CODLOCAL = EST.CODLOCAL
                         AND L.AD_MAXIMA = 'S')) T
/

/*
NomeObjeto: VW_MAXIMA_VEICULOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VEICULOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VEICULOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 22 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODVEICULO || T.DESCRICAO || T.PLACA || T.
                               MARCA || T.VOLUME || T.PESOCARGAKG || T.
                               SITUACAO || T.TIPOVEICULO || T.PROPRIO || T.
                               CODFILIAL || T.TIPO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( V.CODVEICULO ) AS CHAVE
                        , V.CODVEICULO AS CODVEICULO
                        , V.MARCAMODELO || '-' || V.ESPECIETIPO || '-' || V.PLACA
                             AS DESCRICAO
                        , V.PLACA AS PLACA
                        , V.MARCAMODELO AS MARCA
                        , V.M3MAX AS VOLUME
                        , V.PESOMAX AS PESOCARGAKG
                        , CASE WHEN V.ATIVO = 'S' THEN 'L' ELSE 'I' END
                             AS SITUACAO
                        , CASE V.TIPO
                             WHEN 'C' THEN 'L' -- Leve
                             WHEN 'R' THEN 'M' -- Medio
                             WHEN 'B' THEN 'P' -- Pesado
                             WHEN 'E' THEN 'E' -- Extra Pesado
                             ELSE 'L'
                          END
                             AS TIPOVEICULO
                        , V.PROPRIO AS PROPRIO
                        , V.CODPARC AS CODFILIAL
                        , V.TIPO AS TIPO
                        , U.UF AS UFPLACAVEICULO
                        , C.NOMECID AS CIDADEPLACAVEICULO
                     FROM TGFVEI V, TSICID C, TSIUFS U
                    WHERE V.CODCID = C.CODCID
                      AND U.CODUF = C.UF
                      AND V.AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_MOTORISTAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MOTORISTAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MOTORISTAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 46 )
                     AS MD5
                , SNK_GET_MD5(
                               T.MATRICULA || T.TIPO || T.NOME || T.EMAIL ||
                               T.ENVIAFV || T.FONE || T.CELULAR || T.
                               CODFILIAL || TO_CHAR( T.DATA_VALIDADE_CNH
                                                   ,'YYYY-MM-DD HH24:MI:SS' )
                               || T.CPF || T.SITUACAO || T.CODMOTORISTA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( PAR.CODPARC ) AS CHAVE
                        , PAR.CODPARC AS MATRICULA
                        , 'M' AS TIPO /* F - FUNCIONARIO M - MOTORISTA */  
                        , PAR.NOMEPARC AS NOME 
                        , PAR.EMAIL AS EMAIL
                        , 'S' AS ENVIAFV
                        , PAR.TELEFONE AS FONE
                        , CPL.TELTRAB AS CELULAR
                        , PAR.CODEMP AS CODFILIAL
                        , CPL.VENCIMENTOCNH AS DATA_VALIDADE_CNH
                        , PAR.CGC_CPF AS CPF
                        , CASE WHEN PAR.ATIVO = 'S' THEN 'A' ELSE 'I' END
                             AS SITUACAO
                        , PAR.CODPARC AS CODMOTORISTA
                     FROM TGFPAR PAR, TGFCPL CPL
                    WHERE PAR.MOTORISTA = 'S'
                      AND PAR.AD_MAXIMA_MOTORISTA = 'S'
                      AND PAR.CODPARC = CPL.CODPARC) T) T2
/

/*
NomeObjeto: VW_MAXIMA_FUNCIONARIOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FUNCIONARIOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FUNCIONARIOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 26 )
                     AS MD5
                , SNK_GET_MD5(
                               T.MATRICULA || T.TIPO || T.NOME || T.EMAIL ||
                               T.ENVIAFV || T.FONE || T.CELULAR || T.
                               CODFILIAL || TO_CHAR( T.DATA_VALIDADE_CNH
                                                   ,'YYYY-MM-DD HH24:MI:SS' )
                               || T.CPF || T.SITUACAO || T.CODMOTORISTA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( USU.CODUSU ) AS CHAVE
                        , USU.CODUSU AS MATRICULA
                        , 'F' AS TIPO /* F - FUNCIONARIO M - MOTORISTA */  
                        , NOMEUSU AS NOME
                        , USU.EMAIL AS EMAIL
                        , 'S' AS ENVIAFV
                        , TELEFONE AS FONE
                        , CELULAR AS CELULAR
                        , USU.CODEMP AS CODFILIAL
                        , VENCIMENTOCNH AS DATA_VALIDADE_CNH
                        , FUN.CPF AS CPF
                        , CASE WHEN DTDEM IS NULL THEN 'A' ELSE 'I' END
                             AS SITUACAO
                        , USU.CODUSU AS CODMOTORISTA
                     FROM TSIUSU USU, TFPFUN FUN
                    WHERE USU.AD_MAXIMA = 'S'
                      AND USU.CODFUNC = FUN.CODFUNC) T) T2
/

/*
NomeObjeto: VW_MAXIMA_ROTAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ROTAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ROTAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 47 )
                     AS MD5
                , SNK_GET_MD5( T.CODROTA || T.DESCRICAO || T.SITUACAO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CODREG ) AS CHAVE
                        , CODREG AS CODROTA
                        , NOMEREG AS DESCRICAO
                        , CASE WHEN ATIVA = 'S' THEN 'A' ELSE 'I' END
                             AS SITUACAO
                     FROM TSIREG) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CORTE_PDS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CORTE_PDS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CORTE_PDS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 48 )
                     AS MD5
                , SNK_GET_MD5( T.CODPROD || T.NUMPED || T.QTCORTADA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( ITE.NUNOTA ) AS CHAVE
                        , ITE.CODPROD AS CODPROD
                        , ITE.NUNOTA AS NUMPED
                        , ITE.QTDNEG - ITE.QTDENTREGUE AS QTCORTADA
                     FROM TGFITE ITE, TGFCAB CAB
                    WHERE CAB.NUNOTA = ITE.NUNOTA
                      AND ITE.NUNOTA IN
                             ( SELECT NUNOTA
                                FROM VW_MAXIMA_HISTORICO_PD_CAPAS )
                      AND EXISTS
                             (SELECT 1
                                FROM TGFCAB C
                               WHERE C.STATUSNFE IN ('A', 'S') /* NOTAS FATURADAS E APROVADAS NA SEFAZ */  
                                 AND C.NUNOTA = SNK_GET_NOTA_MAXIMA( ITE.NUNOTA ))
                      AND ITE.QTDNEG - ITE.QTDENTREGUE > 0) T) T2
/

/*
NomeObjeto: VW_MAXIMA_FLEX_TABELA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FLEX_TABELA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FLEX_TABELA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 50 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODDESCONTO || T.DTINICIO || T.DTFIM || T.
                               BASECREDDEBRCA || T.CREDITASOBREPOLITICA || T
                               .TIPO || T.PERCDESC || T.NUMREGIAO || T.
                               CODLINHAPROD )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( N.CODTAB ) AS CHAVE
                        , ROWNUM AS CODDESCONTO
                        , '01/01/1900' AS DTINICIO
                        , '01/01/2200' AS DTFIM
                        , 'S' AS BASECREDDEBRCA
                        , 'S' AS CREDITASOBREPOLITICA
                        , 'C' AS TIPO
                        , ( SELECT PERCENTUAL
                             FROM TGFTAB T
                            WHERE T.CODTAB = N.CODTABFLEX
                              AND T.NUTAB =
                                     ( SELECT MAX( T2.NUTAB )
                                        FROM TGFTAB T2
                                       WHERE T2.CODTAB = N.CODTABFLEX
                                         AND T2.DTVIGOR =
                                                ( SELECT MAX( T3.DTVIGOR )
                                                   FROM TGFTAB T3
                                                  WHERE T3.CODTAB =
                                                           N.CODTABFLEX
                                                    AND T3.DTVIGOR <=
                                                           TRUNC( SYSDATE ) ) ) )
                             AS PERCDESC
                        , CODTAB AS NUMREGIAO
                        , NULL AS CODLINHAPROD
                     FROM TGFNTA N
                    WHERE N.CODTABFLEX IS NOT NULL
                      AND N.AD_MAXIMA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_PROMOCOES
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROMOCOES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROMOCOES AS
   SELECT *
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 49 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODDESCONTO || TO_CHAR( T.DTINICIO
                                                       ,
                               'YYYY-MM-DD HH24:MI:SS' ) || TO_CHAR( T.DTFIM
                               , 'YYYY-MM-DD HH24:MI:SS' ) || T.CODFILIAL ||
                               T.CODPROD || T.BASECREDDEBRCA || T.
                               CREDITASOBREPOLITICA || T.PERCDESC || T.TIPO
                               || T.NUMREGIAO || T.CODLINHAPROD || T.CODCLI
                               || T.QTINI || T.QTFIM )
                     AS MD5LINHA
                , T.*
             FROM ( /* PROMOCOES QUE NAO SAO POR QUANTIDADE */  
                   SELECT LPAD( DES.NUPROMOCAO, 10, 0 ) || LPAD( PRO.CODPROD
                   , 10, 0 )
                      AS CHAVE
                        ,LPAD( DES.NUPROMOCAO, 10, 0 ) || LPAD( PRO.CODPROD
                                                              ,10
                                                              ,0 )
                      AS CODDESCONTO
                        ,DTINICIAL AS DTINICIO
                        ,DTFINAL AS DTFIM
                        ,CODEMP AS CODFILIAL
                        ,CASE
                      WHEN PRO.CODPROD = 0 THEN NULL
                      ELSE PRO.CODPROD
                   END
                      AS CODPROD
                        ,'N' AS BASECREDDEBRCA
                        ,'N' AS CREDITASOBREPOLITICA
                        ,DES.PERCENTUAL AS PERCDESC
                        ,'C' AS TIPO
                        ,DES.CODTAB AS NUMREGIAO
                        ,NULL AS CODLINHAPROD
                        ,'F' AS ORIGEMPED
                        ,CASE
                      WHEN DES.CODPARC = 0 THEN NULL
                      ELSE DES.CODPARC
                   END
                      AS CODCLI
                        ,0 AS QTINI
                        ,0 AS QTFIM
                        ,'N' AS APLICADESCONTO
                        ,'N' AS ALTERAPTABELA
                        ,'N' AS PRIORITARIA
                     FROM TGFDES DES, TGFPRO PRO
                    WHERE DES.GRUPODESCPARC = '***************'
                      AND DES.GRUPODESCVEND = '***************'
                      AND DES.CODLOCAL = 0
                      AND DES.VLRVENDA = 0
                      AND NVL( DES.USADESCQTD, 'N' ) = 'N'
                      AND( ( DES.CODPROD <> 0
                        AND DES.CODPROD = PRO.CODPROD )
                       OR( DES.GRUPODESCPROD <> '***************'
                      AND DES.GRUPODESCPROD = PRO.GRUPODESCPROD )
                       OR( DES.CODPROD = 0
                      AND DES.CODPARC <> 0
                      AND DES.GRUPODESCPROD = '***************' ) )
                      AND TRUNC( SYSDATE ) BETWEEN DES.DTINICIAL
                                               AND DES.DTFINAL
                   UNION
                   /* PROMOCOES POR QUANTIDADE */  

                   SELECT T.PROM || T.PROD || T.QTFIM AS CHAVE
                        ,T.PROM || T.PROD || T.QTFIM AS CODDESCONTO
                        ,T.DTINICIO
                        ,T.DTFIM
                        ,T.CODFILIAL
                        ,T.CODPROD
                        ,T.BASECREDDEBRCA
                        ,T.CREDITASOBREPOLITICA
                        ,T.PERCDESC
                        ,T.TIPO
                        ,T.NUMREGIAO
                        ,T.CODLINHAPROD
                        ,T.ORIGEMPED
                        ,T.CODCLI
                        ,T.QTINI
                        ,T.QTFIM
                        ,'S' AS APLICADESCONTO
                        ,'S' AS ALTERAPTABELA
                        ,'S' AS PRIORITARIA
                     FROM (SELECT LPAD( DES.NUPROMOCAO, 6, 0 ) AS PROM
                                ,LPAD( PRO.CODPROD, 6, 0 ) AS PROD
                                ,DES.DTINICIAL AS DTINICIO
                                ,DES.DTFINAL AS DTFIM
                                ,DES.CODEMP AS CODFILIAL
                                ,PRO.CODPROD AS CODPROD
                                ,'N' AS BASECREDDEBRCA
                                ,'N' AS CREDITASOBREPOLITICA
                                ,DPQ.PERCDESC AS PERCDESC
                                ,'C' AS TIPO
                                ,DES.CODTAB AS NUMREGIAO
                                ,NULL AS CODLINHAPROD
                                ,'F' AS ORIGEMPED
                                ,CASE
                      WHEN DES.CODPARC = 0 THEN NULL
                      ELSE DES.CODPARC
                   END
                      AS CODCLI
                                ,NVL( ( SELECT MAX( QTDE ) AS QTD
                                         FROM TGFDPQ D
                                        WHERE D.NUPROMOCAO = DPQ.NUPROMOCAO
                                          AND D.QTDE < DPQ.QTDE ) + 0.01
                                    ,1 )
                      AS QTINI
                                ,DPQ.QTDE AS QTFIM
                             FROM TGFDES DES, TGFPRO PRO, TGFDPQ DPQ
                            WHERE DES.GRUPODESCPARC = '***************'
                              AND DES.GRUPODESCVEND = '***************'
                              AND DES.CODLOCAL = 0
                              AND NVL( DES.VLRVENDA, 0 ) = 0
                              AND NVL( DES.USADESCQTD, 'N' ) = 'S'
                              AND DPQ.NUPROMOCAO = DES.NUPROMOCAO
                              AND( ( DES.CODPROD <> 0
                                AND DES.CODPROD = PRO.CODPROD )
                               OR( DES.GRUPODESCPROD <> '***************'
                              AND DES.GRUPODESCPROD = PRO.GRUPODESCPROD ) )
                              AND TRUNC( SYSDATE ) BETWEEN DES.DTINICIAL
                                                       AND DES.DTFINAL) T) T) T2
/

/*
NomeObjeto: VW_MAXIMA_VISITAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VISITAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VISITAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 51 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCOMPROMISSO || T.CODCLI || T.CODUSUR ||
                               T.SEQUENCIA || T.NUMSEMANA || T.PERIODICIDADE
                               || T.DIASEMANA )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CODVEND, 5, 0 ) || LPAD( CODPARC, 10
                                   , 0 ) )
                             AS CHAVE
                        , ROWNUM AS CODCOMPROMISSO
                        , CODPARC AS CODCLI
                        , CODVEND AS CODUSUR
                        , SEQVISITA AS SEQUENCIA
                        , CASE TIPO
                             WHEN 'P' THEN 1
                             WHEN 'E' THEN 2
                             WHEN '3' THEN 3
                             WHEN '4' THEN 4
                             WHEN '5' THEN 5
                             ELSE 1
                          END
                             AS NUMSEMANA
                        , 0 AS PERIODICIDADE
                        , CASE VALOR
                             WHEN 1 THEN 'DOMINGO'
                             WHEN 2 THEN 'SEGUNDA'
                             WHEN 3 THEN 'TERCA'
                             WHEN 4 THEN 'QUARTA'
                             WHEN 5 THEN 'QUINTA'
                             WHEN 6 THEN 'SEXTA'
                             WHEN 7 THEN 'SABADO'
                          END
                             AS DIASEMANA
                     FROM TGFVIS) T) T2
/

/*
NomeObjeto: VW_MAXIMA_NOTAS_SAIDA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_NOTAS_SAIDA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_NOTAS_SAIDA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 43 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMCAR || T.NUMNOTA || T.NUMPED || T.SERIE
                               || T.CODUSUR || T.CONDVENDA || T.NUMTRANSVENDA
                               || TO_CHAR( T.DTFAT, 'YYYY-MM-DD HH24:MI:SS' ) 
                               || TO_CHAR( T.DTSAIDA, 'YYYY-MM-DD HH24:MI:SS' )
                               || TO_CHAR( T.DTENTREGA, 'YYYY-MM-DD HH24:MI:SS' )
                               || T.CODFILIAL || TO_CHAR( T.DTCANCEL
                                                          ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.VLRTOTAL || T.
                               STATUSNFE || T.MOTIVONFE || T.ESPECIE || T.
                               CODCLI || T.CODPLPAG || T.CODCOB )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CAB.NUNOTA ) AS CHAVE
                        ,CASE WHEN CAB.AD_MAXIMA_NUMCAR IS NOT NULL 
                            THEN CAB.AD_MAXIMA_NUMCAR
                         WHEN ( SELECT MAX(AD_MAXIMA_NUMCAR) FROM TGFCAB C WHERE C.CODEMP = CAB.CODEMP AND C.ORDEMCARGA = CAB.ORDEMCARGA) IS NOT NULL 
                            THEN (SELECT MAX(AD_MAXIMA_NUMCAR) FROM TGFCAB C WHERE C.CODEMP = CAB.CODEMP AND C.ORDEMCARGA = CAB.ORDEMCARGA)
                         WHEN CAB.ORDEMCARGA IS NOT NULL 
                            THEN 'OC' || TO_CHAR(LPAD( CAB.CODEMP, 5, 0 ) || LPAD( CAB.ORDEMCARGA, 10, 0 )) 
                         ELSE NULL END AS NUMCAR
                        ,CAB.NUMNOTA AS NUMNOTA
                        ,SNK_GET_PD_MAXIMA( CAB.NUNOTA ) AS NUMPED
                        ,CAB.SERIENOTA AS SERIE
                        ,CAB.CODVEND AS CODUSUR
                        ,NVL( TPO.AD_MAXIMA_TIPOVENDA, 1 ) AS CONDVENDA
                        ,CAB.NUNOTA AS NUMTRANSVENDA
                        ,CAB.DTFATUR AS DTFAT
                        ,CAB.DTFATUR AS DTSAIDA
                        ,CAB.HRENTSAI AS DTENTREGA
                        ,CAB.CODEMP AS CODFILIAL
                        ,NULL AS DTCANCEL
                        ,CAB.VLRNOTA AS VLRTOTAL
                        ,CAB.STATUSNFE
                        ,( SELECT CAST( A.OCORRENCIAS AS VARCHAR( 400 ) )
                            FROM TGFACT A
                           WHERE A.NUNOTA = CAB.NUNOTA
                             AND A.DHOCOR || A.HRACT || A.SEQUENCIA =
                      (          SELECT MAX(
                   A2.DHOCOR || A2.HRACT || A2.SEQUENCIA )
                                   FROM TGFACT A2
                                  WHERE A2.NUNOTA = A.NUNOTA ) )
                      AS MOTIVONFE
                        ,'NF' AS ESPECIE
                        ,CAB.CODPARC AS CODCLI
                        ,CAB.CODTIPVENDA AS CODPLPAG
                        ,( SELECT MAX( CODTIPTIT )
                            FROM TGFFIN F
                           WHERE F.NUNOTA = CAB.NUNOTA )
                      AS CODCOB
                     FROM TGFCAB CAB
                        ,TGFTOP TPO
                        ,(SELECT QTD_DIAS_NOTAS
                               ,( SELECT CODTIPOPER
                                   FROM TGFCAB
                                  WHERE NUNOTA = MODELOREMESSA )
                      AS TOP_REMESSA
                            FROM AD_MAXCONF) CONF
                    WHERE CAB.TIPMOV = 'V'
                      AND CAB.STATUSNOTA = 'L'
                      AND CAB.STATUSNFE IN ('A', 'S')
                      AND TPO.CODTIPOPER = CAB.CODTIPOPER
                      AND TPO.DHALTER = CAB.DHTIPOPER
                      AND CAB.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS
                   UNION
                   SELECT TO_CHAR( EXC.NUNOTA ) AS CHAVE
                        ,'0' AS NUMCAR
                        ,EXC.NUMNOTA AS NUMNOTA
                        ,0 AS NUMPED
                        ,EXC.SERIENOTA AS SERIE
                        ,EXC.CODVEND AS CODUSUR
                        ,NVL( TPO.AD_MAXIMA_TIPOVENDA, 1 ) AS CONDVENDA
                        ,EXC.NUNOTA AS NUMTRANSVENDA
                        ,EXC.DTFATUR AS DTFAT
                        ,EXC.DTFATUR AS DTSAIDA
                        ,NULL AS DTENTREGA
                        ,EXC.CODEMP AS CODFILIAL
                        ,CAN.DTCANC AS DTCANCEL
                        ,EXC.VLRNOTA AS VLRTOTAL
                        ,EXC.STATUSNFE
                        ,( SELECT CAST( A.OCORRENCIAS AS VARCHAR( 400 ) )
                            FROM TGFACT A
                           WHERE A.NUNOTA = EXC.NUNOTA
                             AND A.DHOCOR || A.HRACT || A.SEQUENCIA =
                      (          SELECT MAX(
                   A2.DHOCOR || A2.HRACT || A2.SEQUENCIA )
                                   FROM TGFACT A2
                                  WHERE A2.NUNOTA = A.NUNOTA ) )
                      AS MOTIVONFE
                        ,'NF' AS ESPECIE
                        ,EXC.CODPARC AS CODCLI
                        ,EXC.CODTIPVENDA AS CODPLPAG
                        ,( SELECT MAX( CODTIPTIT )
                            FROM TGFFIN F
                           WHERE F.NUNOTA = EXC.NUNOTA )
                      AS CODCOB
                     FROM TGFCAN CAN
                   INNER JOIN TGFCAB_EXC EXC ON CAN.NUNOTA = EXC.NUNOTA
                        ,TGFTOP TPO
                        ,(SELECT QTD_DIAS_NOTAS
                               ,( SELECT CODTIPOPER
                                   FROM TGFCAB
                                  WHERE NUNOTA = MODELOREMESSA )
                      AS TOP_REMESSA
                            FROM AD_MAXCONF) CONF
                    WHERE EXC.TIPMOV = 'V'
                      AND EXC.STATUSNOTA = 'L'
                      AND EXC.STATUSNFE IN ('A', 'S')
                      AND TPO.CODTIPOPER = EXC.CODTIPOPER
                      AND TPO.DHALTER = EXC.DHTIPOPER
                      AND EXC.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS) T) T2
/

/*
NomeObjeto: VW_MAXIMA_NOTAS_SAIDA_ITENS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_NOTAS_SAIDA_ITENS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_NOTAS_SAIDA_ITENS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 60 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMCAR || T.NUMNOTA || T.NUMPED || T.CODPROD
                               || T.QT || T.NUMTRANSVENDA || T.NUMTRANSITEM
                               || T.CODAUXILIAR || T.CODOPER || T.QTCONT ||
                               T.PTABELA || T.PUNITCONT || T.PUNIT || T.
                               CUSTOFIN || T.VLIPI || T.ST || T.QTDEVOL )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( ITE.NUNOTA, 10, 0 ) || LPAD(
                                   ITE.SEQUENCIA
                                                                    ,5
                                                                    ,0 ) )
                             AS CHAVE
                        ,CASE WHEN CAB.AD_MAXIMA_NUMCAR IS NOT NULL 
                            THEN CAB.AD_MAXIMA_NUMCAR
                         WHEN ( SELECT MAX(AD_MAXIMA_NUMCAR) FROM TGFCAB C WHERE C.CODEMP = CAB.CODEMP AND C.ORDEMCARGA = CAB.ORDEMCARGA) IS NOT NULL 
                            THEN (SELECT MAX(AD_MAXIMA_NUMCAR) FROM TGFCAB C WHERE C.CODEMP = CAB.CODEMP AND C.ORDEMCARGA = CAB.ORDEMCARGA)
                         WHEN CAB.ORDEMCARGA IS NOT NULL 
                            THEN 'OC' || TO_CHAR(LPAD( CAB.CODEMP, 5, 0 ) || LPAD( CAB.ORDEMCARGA, 10, 0 )) 
                         ELSE NULL END AS NUMCAR
                        , CAB.NUMNOTA AS NUMNOTA
                        , SNK_GET_PD_MAXIMA( CAB.NUNOTA ) AS NUMPED
                        , ITE.CODPROD
                        , ITE.QTDNEG AS QT
                        , ITE.NUNOTA AS NUMTRANSVENDA
                        , ITE.NUNOTA || LPAD( ITE.SEQUENCIA, 5, 0 )
                             AS NUMTRANSITEM
                        , ( SELECT NVL( PRO.REFERENCIA, PRO.CODPROD )
                             FROM TGFPRO PRO
                            WHERE PRO.CODPROD = ITE.CODPROD )
                             AS CODAUXILIAR
                        , 'S' AS CODOPER
                        , ITE.QTDNEG AS QTCONT
                        , ITE.VLRCUS AS PTABELA
                        , ITE.VLRUNIT AS PUNITCONT
                        , ITE.VLRUNIT - ITE.VLRDESC / CASE WHEN NVL( ITE.QTDNEG , 1 ) = 0 THEN 1 ELSE NVL( ITE.QTDNEG , 1 ) END AS PUNIT
                        , 0 AS CUSTOFIN
                        , ITE.VLRIPI AS VLIPI
                        , ITE.VLRSUBST AS ST
                        , ( SELECT SUM( I.QTDNEG )
                             FROM TGFITE I, TGFCAB C, TGFVAR V
                            WHERE ITE.NUNOTA = V.NUNOTAORIG
                              AND ITE.SEQUENCIA = V.SEQUENCIAORIG
                              AND I.NUNOTA = V.NUNOTA
                              AND I.SEQUENCIA = V.SEQUENCIA
                              AND C.NUNOTA = V.NUNOTA
                              AND C.TIPMOV = 'D'
                              AND C.STATUSNOTA = 'L'
                              AND C.STATUSNFE = 'A'
                              AND I.CODLOCALORIG = ITE.CODLOCALORIG )
                             AS QTDEVOL
                     FROM TGFITE ITE, TGFCAB CAB
                    WHERE CAB.NUNOTA = ITE.NUNOTA
                      AND ITE.NUNOTA IN
                             ( SELECT NUMTRANSVENDA
                                FROM VW_MAXIMA_NOTAS_SAIDA )) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CARREGAMENTOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CARREGAMENTOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CARREGAMENTOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 38 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMCAR || TO_CHAR( T.DATAMON
                                                  ,'YYYY-MM-DD HH24:MI:SS' )
                               || TO_CHAR( T.DTFECHA, 'YYYY-MM-DD HH24:MI:SS'
                               ) || TO_CHAR( T.DTSAIDA
                                           ,'YYYY-MM-DD HH24:MI:SS' ) ||
                               TO_CHAR                                   (
                               T.DTFAT
                                                                          ,
                               'YYYY-MM-DD HH24:MI:SS' ) || ORIGEM_CAR ||
                               CODMOTORISTA || T.CODVEICULO || TOTPESO ||
                               TOTVOLUME || VLTOTAL || T.NUMNOTAS || DESTINO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                   LPAD            ( ORD.CODEMP, 5, 0 ) || LPAD(
                   ORD.ORDEMCARGA
                                                               ,10
                                                               ,0 ) )
                      AS CHAVE
                        ,NVL(
                   AD_MAXIMA_NUMCAR
                            ,'OC' || TO_CHAR(
                   LPAD                       ( ORD.CODEMP, 5, 0 ) || LPAD(
                   ORD.ORDEMCARGA
                                                                          ,
                   10
                                                                          ,0
                   ) ) )
                      AS NUMCAR
                        ,ORD.DTALTER AS DATAMON
                        ,DTRETORNO AS DTFECHA
                        ,DTPREVSAIDA AS DTSAIDA
                        ,( SELECT MIN( C.DTFATUR )
                            FROM TGFCAB C
                           WHERE C.CODEMP = ORD.CODEMP
                             AND C.ORDEMCARGA = ORD.ORDEMCARGA
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                   )
                      AS DTFAT
                        ,CASE
                      WHEN AD_MAXIMA_NUMCAR = NULL THEN 'ERP'
                      ELSE ''
                   END
                      AS ORIGEM_CAR
                        ,ORD.CODPARCMOTORISTA AS CODMOTORISTA
                        ,ORD.CODVEICULO
                        ,( SELECT SUM( C.PESOBRUTO )
                            FROM TGFCAB C
                           WHERE C.CODEMP = ORD.CODEMP
                             AND C.ORDEMCARGA = ORD.ORDEMCARGA
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                   )
                      AS TOTPESO
                        ,( SELECT SUM( C.PESOBRUTO )
                            FROM TGFCAB C
                           WHERE C.CODEMP = ORD.CODEMP
                             AND C.ORDEMCARGA = ORD.ORDEMCARGA
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                   )
                      AS TOTVOLUME
                        ,( SELECT SUM( C.VLRNOTA )
                            FROM TGFCAB C
                           WHERE C.CODEMP = ORD.CODEMP
                             AND C.ORDEMCARGA = ORD.ORDEMCARGA
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                   )
                      AS VLTOTAL
                        ,( SELECT COUNT( 1 )
                            FROM TGFCAB C
                           WHERE C.CODEMP = ORD.CODEMP
                             AND C.ORDEMCARGA = ORD.ORDEMCARGA
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                   )
                      AS NUMNOTAS
                        ,( SELECT NOMEREG
                            FROM TSIREG REG
                           WHERE REG.CODREG = ORD.CODREG )
                      AS DESTINO
                     FROM TGFORD ORD
                        ,(SELECT QTD_DIAS_CARREGAMENTO, TOP_ORCAMENTO
                            FROM AD_MAXCONF) CONF
                    WHERE NVL( DTRETORNO, TRUNC( SYSDATE ) ) >=
                      TRUNC( SYSDATE ) - CONF.QTD_DIAS_CARREGAMENTO
                      AND EXISTS
                      (   SELECT 1
                            FROM TGFCAB CAB
                           WHERE CAB.CODEMP = ORD.CODEMP
                             AND CAB.ORDEMCARGA = ORD.ORDEMCARGA)
                   UNION
                   SELECT CAST( 'PE' || NUMCAR AS VARCHAR( 50 ) ) AS CHAVE
                        ,CAST( 'PE' || NUMCAR AS VARCHAR( 50 ) ) AS NUMCAR
                        ,NULL AS DATAMON
                        ,DTFECHAMENTO AS DTFECHA
                        ,TRUNC( SYSDATE ) AS DTSAIDA
                        ,TRUNC( SYSDATE ) AS DTFAT
                        ,'' ORIGEM_CAR
                        ,NULL AS CODMOTORISTA
                        ,NULL AS CODVEICULO
                        ,NULL AS TOTPESO
                        ,NULL AS TOTVOLUME
                        ,NULL AS VLTOTAL
                        ,( SELECT COUNT( 1 )
                            FROM TGFCAB C, TGFTOP TPO
                           WHERE TPO.CODTIPOPER = C.CODTIPOPER
                             AND TPO.DHALTER = C.DHTIPOPER
                             AND TPO.AD_MAXIMA_TIPOVENDA IS NOT NULL
                             AND C.TIPMOV = 'P'
                             AND C.CODTIPOPER <> NVL( CONF.TOP_ORCAMENTO, 0 )
                             AND C.AD_MAXIMA_NUMCAR = 'PE' || CAR.NUMCAR )
                      AS NUMNOTAS
                        ,NULL AS DESTINO
                     FROM AD_MAXIMA_CARREGAMENTOS CAR
                        ,(SELECT QTD_DIAS_CARREGAMENTO, TOP_ORCAMENTO
                            FROM AD_MAXCONF) CONF
                    WHERE NVL( DTFECHAMENTO, TRUNC( SYSDATE ) ) >=
                      TRUNC( SYSDATE ) - CONF.QTD_DIAS_CARREGAMENTO) T) T2
/

/*
NomeObjeto: VW_MAXIMA_FECHAMENTO_VENDEDOR
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FECHAMENTO_VENDEDOR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FECHAMENTO_VENDEDOR AS
   SELECT C.NUMCAR
        , C.CODVEND
        , V.APELIDO
        , C.DTABERTURA
     FROM AD_MAXIMA_CARREGAMENTOS C JOIN TGFVEN V ON C.CODVEND = V.CODVEND
    WHERE C.DTFECHAMENTO IS NULL
      AND V.AD_MAXIMA = 'S'
/

/*
NomeObjeto: VW_MAXIMA_REMESSA_SIMBOLICA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_REMESSA_SIMBOLICA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_REMESSA_SIMBOLICA AS
   SELECT *
     FROM TGFCAB CAB /* CAB RETORNO */  
        , (SELECT MODELORETORNO, QTD_DIAS_NOTAS, TOP_NF_RETORNO
             FROM AD_MAXCONF) CONF
    WHERE CAB.TIPMOV = 'D'
      AND CAB.CODTIPOPER = (CONF.TOP_NF_RETORNO)
      AND CAB.NUNOTA = (SELECT MAX( NUNOTA )
                          FROM TGFCAB C
                         WHERE C.CODTIPOPER = CAB.CODTIPOPER
                           AND C.CODVEND = CAB.CODVEND)
      AND EXISTS
             (SELECT 1
                FROM TGFVEN VEN
               WHERE VEN.CODVEND = CAB.CODVEND
                 AND VEN.ATIVO = 'S')
      AND NOT EXISTS
             (SELECT 1
                FROM TGFVAR V, TGFCAB CR /* CAB REMESSA */  
                                        , TGFTOP TPO
               WHERE V.NUNOTAORIG = CAB.NUNOTA
                 AND V.NUNOTA = CR.NUNOTA
                 AND CR.CODVEND = CAB.CODVEND
                 AND TPO.CODTIPOPER = CR.CODTIPOPER
                 AND TPO.DHALTER = CR.DHTIPOPER
                 AND CR.TIPMOV = 'V')
/

/*
NomeObjeto: VW_MAXIMA_REMESSA_SIMBOLICA_D
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_REMESSA_SIMBOLICA_D
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_REMESSA_SIMBOLICA_D AS
   SELECT ITE.*
     FROM TGFITE ITE
    WHERE ITE.NUNOTA = (SELECT NUNOTA FROM VW_MAXIMA_REMESSA_SIMBOLICA)
/

/*
NomeObjeto: VW_MAXIMA_ENTRADAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ENTRADAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ENTRADAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 65 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMTRANSENT || T.CODCONT || T.CODDEVOL || T
                               .CODFILIAL || T.CODFISCAL || T.CODOPERACAO ||
                               TO_CHAR
                               ( T.DTENT, 'YYYY-MM-DD HH24:MI:SS' ) || T.
                               ESPECIE || T.SERIE || T.NUMNOTA || T.OBS || T
                               .UF || T.TOTPESO || T.VLFRETE || T.VLST || T.
                               CODMOTORISTADEVOL || T.CODUSURDEVOL || T.
                               SITUACAONFE || T.GERANFDEVCLI || T.CODPARC )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CAB.NUNOTA ) AS CHAVE
                        , CAB.NUNOTA AS NUMTRANSENT
                        , 0 AS CODCONT
                        , 1 AS CODDEVOL
                        , CAB.CODEMP AS CODFILIAL
                        , CASE
                             WHEN UF_PAR.UF = UF_EMP.UF THEN
                                TPO.CODCFO_ENTRADA
                             ELSE
                                TPO.CODCFO_ENTRADA_FORA
                          END
                             AS CODFISCAL
                        , 'ED' AS CODOPERACAO
                        , CAB.DTNEG AS DTENT
                        , 'NF' AS ESPECIE
                        , CAB.SERIENOTA AS SERIE
                        , CAB.NUMNOTA AS NUMNOTA
                        , CAST( OBSERVACAO AS VARCHAR2( 255 ) ) AS OBS
                        , UF_PAR.UF AS UF
                        , NVL( CAB.PESO, 0 ) AS TOTPESO
                        , NVL( CAB.VLRFRETE, 0 ) AS VLFRETE
                        , CAB.VLRSUBST AS VLST
                        , CAB.CODMOTORISTA AS CODMOTORISTADEVOL
                        , CAB.CODVEND AS CODUSURDEVOL
                        , 0 AS SITUACAONFE
                        , CASE WHEN TPO.NFE = 'T' THEN 'N' ELSE 'S' END
                             AS GERANFDEVCLI
                        , CAB.CODPARC 
                     FROM TGFCAB CAB
                        , TGFTOP TPO
                        , TGFPAR PAR
                        , TSICID CID_PAR
                        , TSICID CID_EMP
                        , TSIUFS UF_PAR
                        , TSIUFS UF_EMP
                        , TSIEMP EMP
                        , (SELECT QTD_DIAS_NOTAS FROM AD_MAXCONF) CONF
                    WHERE CAB.TIPMOV IN ('C', 'D') /* COMPRA E DEVOLUCAO DE VENDA */  
                      AND CAB.DTNEG >= TRUNC( SYSDATE ) - CONF.QTD_DIAS_NOTAS
                      AND CAB.STATUSNOTA = 'L' /* CONFIRMADA */  
                      AND ( CAB.TPEMISNFE IS NULL OR CAB.STATUSNFE IN ('A', 'S') ) /* APROVADA SEFAZ */  
                      AND TPO.CODTIPOPER = CAB.CODTIPOPER
                      AND TPO.DHALTER = CAB.DHTIPOPER
                      AND PAR.CODPARC = CAB.CODPARC
                      AND EMP.CODEMP = CAB.CODEMP
                      AND CID_PAR.CODCID = PAR.CODCID
                      AND UF_PAR.CODUF = CID_PAR.UF
                      AND CID_EMP.CODCID = EMP.CODCID
                      AND UF_EMP.CODUF = CID_EMP.UF) T) T2
/

/*
NomeObjeto: VW_MAXIMA_ENTRADAS_ITENS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ENTRADAS_ITENS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ENTRADAS_ITENS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 66 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMTRANSITEM || T.NUMTRANSVENDA || T.NUMCAR
                               || T.NUMNOTA || T.NUMPED || T.CODPROD || T.QT
                               || T.QTCONT || T.NUMSEQ || T.CODOPER || T.
                               PTABELA || T.PUNITCONT || T.PUNIT || T.
                               CUSTOFIN || T.VLIPI || T.ST || T.CODDEVOL ||
                               T.NUMTRANSENT || T.QTDEVOL || T.CODAUXILIAR )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( ITE.NUNOTA, 10, 0 ) || LPAD(
                                   ITE.SEQUENCIA
                                                                    ,5
                                                                    ,0 ) )
                             AS CHAVE
                        , ITE.NUNOTA || LPAD( ITE.SEQUENCIA, 5, 0 )
                             AS NUMTRANSITEM
                        , NULL AS NUMTRANSVENDA
                        , CAB.AD_MAXIMA_NUMCAR AS NUMCAR
                        , CAB.NUMNOTA AS NUMNOTA
                        , ( SELECT MAX( V.NUNOTAORIG )
                             FROM TGFVAR V
                            WHERE V.NUNOTA = (SELECT MAX( V.NUNOTAORIG )
                                                FROM TGFVAR V
                                               WHERE V.NUNOTA = CAB.NUNOTA) )
                             AS NUMPED
                        , ITE.CODPROD
                        , ITE.QTDNEG AS QT
                        , ITE.QTDNEG AS QTCONT
                        , ITE.SEQUENCIA AS NUMSEQ
                        , 'ED' AS CODOPER
                        , ITE.VLRUNIT AS PTABELA
                        , ITE.VLRUNIT AS PUNITCONT
                        , ITE.VLRUNIT - ( ITE.VLRDESC / ITE.QTDNEG ) AS PUNIT
                        , 0 AS CUSTOFIN
                        , ITE.VLRIPI AS VLIPI
                        , ITE.BASESUBSTIT AS ST
                        , 1 AS CODDEVOL
                        , ITE.NUNOTA AS NUMTRANSENT
                        , 0 AS QTDEVOL
                        , ( SELECT NVL( PRO.REFERENCIA, PRO.CODPROD )
                             FROM TGFPRO PRO
                            WHERE PRO.CODPROD = ITE.CODPROD )
                             AS CODAUXILIAR
                     FROM TGFITE ITE, TGFCAB CAB, TGFPRO PRO
                    WHERE CAB.NUNOTA = ITE.NUNOTA
                      AND PRO.CODPROD = ITE.CODPROD
                      AND ITE.NUNOTA IN
                             (SELECT NUMTRANSENT FROM VW_MAXIMA_ENTRADAS)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_ENTRADAS_LIGACOES
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ENTRADAS_LIGACOES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ENTRADAS_LIGACOES AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 67 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMTRANSENT || T.NUMTRANSVENDA || T.
                               DTESTORNO || T.CODUSUR || T.VLESTORNO || T.
                               VLDEVOLUCAO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( NUMTRANSENT, 10, 0 ) || LPAD(
                                   NUMTRANSVENDA
                                                                     ,10
                                                                     ,0 ) )
                             AS CHAVE
                        , T.*
                     FROM (SELECT CAB.NUNOTA AS NUMTRANSENT
                                , ( SELECT MAX( V.NUNOTAORIG )
                                     FROM TGFVAR V
                                    WHERE V.NUNOTA = CAB.NUNOTA )
                                     AS NUMTRANSVENDA
                                , CAB.DTNEG AS DTESTORNO
                                , CAB.CODVEND AS CODUSUR
                                , 0 AS VLESTORNO
                                , CAB.VLRNOTA AS VLDEVOLUCAO
                             FROM TGFCAB CAB
                            WHERE CAB.NUNOTA IN
                                     ( SELECT NUMTRANSENT
                                        FROM VW_MAXIMA_ENTRADAS )) T) T) T2
/

/*
NomeObjeto: VW_MAX_COMPRAS_PENDENTES
TipoObjeto: VIEW
NomeTabela: VW_MAX_COMPRAS_PENDENTES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_COMPRAS_PENDENTES AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 68 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODFILIAL || T.CODPROD || T.DTPREVENT || T.
                               QTPENDENTE || T.SITUACAO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CODFILIAL, 10, 0 ) || LPAD( CODPROD
                                   , 10, 0 ) || LPAD( DTPREVENT, 8, 0 ) )
                             AS CHAVE
                        , T.*
                     FROM (SELECT C.CODEMP AS CODFILIAL
                                , I.CODPROD
                                , MIN( C.DTPREVENT ) AS DTPREVENT
                                , SUM( I.QTDNEG - I.QTDENTREGUE )
                                     AS QTPENDENTE
                                , 'PN' AS SITUACAO
                             FROM TGFCAB C
                                , TGFITE I
                                , (SELECT QTD_DIAS_COMPRAS_PENDENTE
                                     FROM AD_MAXCONF) CONF
                            WHERE C.NUNOTA = I.NUNOTA
                              AND C.TIPMOV = 'O' /* PEDIDO DE COMPRA */  
                              AND C.STATUSNOTA = 'L' /* CONFIRMADA */  
                              AND C.PENDENTE = 'S' /* PENDENTE */  
                              AND C.DTNEG >=
                                     TRUNC( SYSDATE ) - CONF.
                                     QTD_DIAS_COMPRAS_PENDENTE
                              AND C.DTPREVENT IS NOT NULL
                           GROUP BY C.CODEMP, I.CODPROD, C.DTPREVENT) T) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CONTATOS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CONTATOS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CONTATOS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 70 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODCLI || T.CODCONTATO || T.NOMECONTATO ||
                               T.CARGO || TO_CHAR( T.DTNASCIMENTO
                                                 ,'YYYY-MM-DD HH24:MI:SS' )
                               || T.EMAIL || T.TELEFONE || T.CELULAR || T.
                               TIPOCONTATO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CTT.CODPARC, 10, 0 ) || LPAD(
                                   CTT.CODCONTATO
                                                                     ,10
                                                                     ,0 ) )
                             AS CHAVE
                        , CTT.CODPARC AS CODCLI
                        , LPAD( CTT.CODPARC, 10, 0 ) || LPAD( CTT.CODCONTATO
                          , 10, 0 )
                             AS CODCONTATO
                        , CTT.NOMECONTATO
                        , CTT.CARGO
                        , CTT.DTNASC AS DTNASCIMENTO
                        , CTT.EMAIL
                        , CTT.TELEFONE
                        , CTT.CELULAR
                        , CASE WHEN CTT.SOCIO = 'S' THEN 'S' ELSE 'F' END
                             TIPOCONTATO
                     FROM TGFCTT CTT, TGFPAR PAR
                    WHERE PAR.CODPARC = CTT.CODPARC
                      AND PAR.AD_MAXIMA_CLIENTE = 'S'
                      AND PAR.CLIENTE = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_TRANSPORTADORAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TRANSPORTADORAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TRANSPORTADORAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 71 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODTRANSP || T.TRANSPORTADORA || T.FANTASIA
                               || T.CGC || T.ENDERECO || T.BAIRRO || T.CIDADE
                               || T.UF || T.TELEFONE || T.REVENDA || T.
                               BLOQUEIO || T.EREDESPACHO )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( LPAD( PAR.CODPARC, 10, 0 ) ) AS CHAVE
                        , PAR.CODPARC AS CODTRANSP
                        , PAR.RAZAOSOCIAL AS TRANSPORTADORA
                        , PAR.NOMEPARC AS FANTASIA
                        , PAR.CGC_CPF AS CGC
                        , ENDE.NOMEEND AS ENDERECO
                        , BAIRRO.NOMEBAI AS BAIRRO
                        , CID.NOMECID AS CIDADE
                        , UFS.UF AS UF
                        , PAR.TELEFONE AS TELEFONE
                        , 'T' AS REVENDA
                        , CASE WHEN PAR.ATIVO = 'S' THEN 'N' ELSE 'S' END
                             AS BLOQUEIO
                        , 'N' AS EREDESPACHO
                     FROM TGFPAR PAR
                          LEFT JOIN TSIBAI BAIRRO
                             ON BAIRRO.CODBAI = PAR.CODBAI
                          LEFT JOIN TSICID CID ON CID.CODCID = PAR.CODCID
                          LEFT JOIN TSIUFS UFS ON UFS.CODUF = CID.UF
                          LEFT JOIN TSIEND ENDE ON ENDE.CODEND = PAR.CODEND
                    WHERE PAR.AD_MAXIMA_TRANSPORTADORA = 'S'
                      AND PAR.TRANSPORTADORA = 'S') T) T2
/

/*
NomeObjeto: VW_MAXIMA_LOTE_ESTOQUE
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_LOTE_ESTOQUE
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_LOTE_ESTOQUE AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 72 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODFILIAL || T.CODPROD || T.NUMLOTE ||
                               TO_CHAR                                  (
                               T.DATAFABRICACAO
                                                                         ,
                               'YYYY-MM-DD HH24:MI:SS' ) || TO_CHAR(
                               T.DTVALIDADE
                                                                   ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.QT )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( EST.CODEMP, 5, 0 ) || LPAD(
                                   EST.CODPROD
                                                                   ,10
                                                                   ,0 ) ||
                                   EST.CONTROLE )
                             AS CHAVE
                        , EST.CODEMP AS CODFILIAL
                        , EST.CODPROD AS CODPROD
                        , EST.CONTROLE AS NUMLOTE
                        , EST.DTFABRICACAO AS DATAFABRICACAO
                        , EST.DTVAL AS DTVALIDADE
                        , SUM( EST.ESTOQUE - EST.RESERVADO ) AS QT
                     FROM TGFEST EST
                    WHERE EST.TIPO = 'P'
                      AND EST.CODPARC = 0
                      AND EXISTS
                             (SELECT 1
                                FROM TSIEMP E
                               WHERE E.CODEMP = EST.CODEMP
                                 AND E.AD_MAXIMA = 'S')
                      AND EXISTS
                             (SELECT 1
                                FROM TGFPRO P
                               WHERE P.CODPROD = EST.CODPROD
                                 AND P.AD_MAXIMA = 'S')
                      AND EXISTS
                             (SELECT 1
                                FROM TGFLOC L
                               WHERE L.CODLOCAL = EST.CODLOCAL
                                 AND L.AD_MAXIMA = 'S')
                   GROUP BY EST.CODEMP
                          , EST.CODPROD
                          , EST.CONTROLE
                          , EST.DTFABRICACAO
                          , EST.DTVAL
                   HAVING SUM( EST.ESTOQUE - EST.RESERVADO ) > 0) T) T2
/

/*
NomeObjeto: VW_MAXIMA_METAS_VENDAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_METAS_VENDAS
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_METAS_VENDAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 69 )
                     AS MD5
                , SNK_GET_MD5(
                               CODMETA || CODUSUR || TIPOMETA || CODIGO ||
                               CODFILIAL || TO_CHAR( T.DATAINICIAL
                                                   ,'YYYY-MM-DD HH24:MI:SS' )
                               || TO_CHAR( T.DATAFINAL
                                         ,'YYYY-MM-DD HH24:MI:SS' ) ||
                               VLVENDAPREV || QTVENDAPREV )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CFG.CODMETA, 5, 0 ) || LPAD(
                                   MET.CODVEND
                                                                    ,5
                                                                    ,0 ) ||
                                   TO_NUMBER
                                   (
                                   TO_CHAR
                                   ( MET.DTREF, 'yyyymmdd' ) ) )
                             AS CHAVE
                        , TO_NUMBER( TO_CHAR( MET.DTREF, 'yyyymmdd' ) )
                             AS CODMETA
                        , MET.CODVEND AS CODUSUR
                        , 'M' AS TIPOMETA
                        , '0' AS CODIGO
                        , CFG.EMPRESA AS CODFILIAL
                        , MET.DTREF AS DATAINICIAL
                        , LAST_DAY( MET.DTREF ) AS DATAFINAL
                        , NVL( MET.PREVREC, 0 ) AS VLVENDAPREV
                        , NVL( MET.QTDPREV, 0 ) AS QTVENDAPREV
                        , 0 AS QTPESOPREV
                        , 0 AS VOLUMEPREV
                        , 0 AS QTDEPEDIDOSPREV
                        , 0 AS CLISPOSPREV
                     FROM TGMCFG CFG, TGMMET MET
                    WHERE MET.CODMETA = CFG.CODMETA
                      AND CFG.PERIODO = 4) T) T2
/

/*
NomeObjeto: VW_MAXIMA_MENSAGEM_VENDEDORES
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MENSAGEM_VENDEDORES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MENSAGEM_VENDEDORES AS
   SELECT CODMENSAGEM
        , CODVEND AS CODUSUR
        , DTMENSAGEM AS DATA
        , MENSAGEM
        , STATUSMENSAGEM AS STATUS
        , CODUSU AS CODREMETENTE
     FROM AD_MAXIMA_MENSAGENS
    WHERE DTMENSAGEM >= TRUNC( SYSDATE ) - 7
      AND STATUSMENSAGEM IS NULL
/

/*
NomeObjeto: VW_MAXIMA_HISTORICO_PD_ITENS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_HISTORICO_PD_ITENS
Executar  : SEMPRE
*/ 

/* VIEW HISTORICO DE PEDIDOS ITENS */  

CREATE OR REPLACE VIEW VW_MAXIMA_HISTORICO_PD_ITENS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 21 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMPED || T.QT || T.NUMSEQ || T.PVENDA || T
                               .CODPROD || T.PTABELA || T.PERCOM || TO_CHAR(
                               T.DATA
                                                                           ,
                               'YYYY-MM-DD HH24:MI:SS' ) )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( ITE.NUNOTA, 10, 0 ) || LPAD(
                                   ITE.SEQUENCIA
                                                                    ,5
                                                                    ,0 ) )
                             AS CHAVE
                        , ITE.NUNOTA AS NUMPED
                        , ITE.QTDNEG AS QT
                        , ITE.SEQUENCIA AS NUMSEQ
                        , ROUND(
                                 ( ITE.VLRTOT + ITE.VLRSUBST - ITE.VLRDESC ) / CASE
                                    WHEN QTDNEG <> 0 THEN QTDNEG
                                    ELSE 1
                                 END
                               , 2 )
                             AS PVENDA
                        , ITE.CODPROD AS CODPROD
                        , ITE.VLRCUS AS PTABELA
                        , NVL( ITE.PERCCOM, 0 ) AS PERCOM
                        , ( SELECT DTNEG
                             FROM TGFCAB
                            WHERE NUNOTA = ITE.NUNOTA )
                             AS DATA
                     FROM TGFITE ITE
                    WHERE ITE.NUNOTA IN
                             ( SELECT NUNOTA
                                FROM VW_MAXIMA_HISTORICO_PD_CAPAS )
                      AND ITE.USOPROD <> 'D') T) T2
/

/*
NomeObjeto: VW_MAXIMA_MIXCLIENTES
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MIXCLIENTES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MIXCLIENTES AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 13 )
                     AS MD5
                , SNK_GET_MD5(
                               T.NUMTRANSVENDA || T.CODPROD || T.QT || T.
                               CODCLI || T.CODFILIAL || T.PUNIT || TO_CHAR(
                               T.DTSAIDA
                                                                          ,
                               'YYYY-MM-DD HH24:MI:SS' ) || T.PTABELA || T.
                               CODPLPAG || T.VLRVENDA || T.CODAUXILIAR || T.
                               CODUSUR )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR( CAB.NUNOTA ) AS CHAVE
                        , CAB.NUNOTA AS NUMTRANSVENDA
                        , ITE.CODPROD
                        , ITE.QTDNEG AS QT
                        , CAB.CODPARC AS CODCLI
                        , CAB.CODEMP AS CODFILIAL
                        , ITE.VLRUNIT AS PUNIT
                        , CAB.DTENTSAI AS DTSAIDA
                        , ITE.VLRCUS AS PTABELA
                        , CAB.CODTIPVENDA AS CODPLPAG
                        , ITE.VLRUNIT AS VLRVENDA
                        , NVL( PRO.REFERENCIA, ITE.CODPROD ) AS CODAUXILIAR
                        , ITE.CODUSU AS CODUSUR
                     FROM TGFCAB CAB
                          INNER JOIN TGFITE ITE ON ITE.NUNOTA = CAB.NUNOTA
                          INNER JOIN TGFPRO PRO ON PRO.CODPROD = ITE.CODPROD
                        , (SELECT QTD_DIAS_HIST_VENDAS FROM AD_MAXCONF) CONF
                    WHERE CAB.TIPMOV = 'V'
                      AND CAB.STATUSNOTA = 'L'
                      AND CAB.DTNEG >=
                             TRUNC( SYSDATE ) - CONF.QTD_DIAS_HIST_VENDAS) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CODIGO_BARRAS
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CODIGO_BARRAS
Executar  : SE_NAO_EXISTIR
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CODIGO_BARRAS AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 75 )
                     AS MD5
                , SNK_GET_MD5( T.CODPROD || T.CODBARRAS ) AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( CODPROD, 10, 0 ) || LPAD( CODBARRA
                                                                 ,25
                                                                 ,0 ) )
                             AS CHAVE
                        , CODPROD AS CODPROD
                        , CODBARRA AS CODBARRAS
                     FROM TGFBAR) T) T2
/

/*
NomeObjeto: VW_MAXIMA_CODIGO_BARRAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CODIGO_BARRAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CODIGO_BARRAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 75
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CODIGO_BARRAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_LOTE_ESTOQUE_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_LOTE_ESTOQUE_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_LOTE_ESTOQUE_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 72
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_LOTE_ESTOQUE V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CODIGO_BARRAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CODIGO_BARRAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CODIGO_BARRAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 75
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CODIGO_BARRAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_METAS_VENDAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_METAS_VENDAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_METAS_VENDAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 69
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_METAS_VENDAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_TRANSPORTADORAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TRANSPORTADORAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TRANSPORTADORAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 71
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_TRANSPORTADORAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CONTATOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CONTATOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CONTATOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 70
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CONTATOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAX_COMPRAS_PENDENTES_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAX_COMPRAS_PENDENTES_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_COMPRAS_PENDENTES_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 68
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAX_COMPRAS_PENDENTES V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_VISITAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VISITAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VISITAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 51
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_VISITAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PROMOCOES_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROMOCOES_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROMOCOES_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 49
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PROMOCOES V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_FLEX_TABELA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FLEX_TABELA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FLEX_TABELA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 50
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_FLEX_TABELA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_ROTAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ROTAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ROTAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 47
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_ROTAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_FUNCIONARIOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FUNCIONARIOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FUNCIONARIOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 26
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_FUNCIONARIOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_MOTORISTAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MOTORISTAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MOTORISTAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 46
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_MOTORISTAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_VEICULOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VEICULOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VEICULOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 22
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_VEICULOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_BANCOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_BANCOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_BANCOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 53
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_BANCOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_FLEX_SALDO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FLEX_SALDO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FLEX_SALDO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 15
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_FLEX_SALDO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAX_COBRANCAS_PAG_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAX_COBRANCAS_PAG_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_COBRANCAS_PAG_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 35
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAX_COBRANCAS_PAG V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_EMBALAGENS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_EMBALAGENS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_EMBALAGENS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 33
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_EMBALAGENS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_TABELA_PRECO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TABELA_PRECO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TABELA_PRECO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 16
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_TABELA_PRECO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_MIXCLIENTES_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MIXCLIENTES_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MIXCLIENTES_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 13
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_MIXCLIENTES V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PRODUTOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRODUTOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRODUTOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 4
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PRODUTOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_SUBCATEGORIA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SUBCATEGORIA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SUBCATEGORIA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 58
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_SUBCATEGORIA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CATEGORIA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CATEGORIA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CATEGORIA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 57
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CATEGORIA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_SECAO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SECAO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SECAO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 56
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_SECAO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_DEPARTAMENTO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_DEPARTAMENTO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_DEPARTAMENTO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 5
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_DEPARTAMENTO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_FORNECEDOR_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_FORNECEDOR_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_FORNECEDOR_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 18
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_FORNECEDOR V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CLIENTE_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CLIENTE_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CLIENTE_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 3
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CLIENTE V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_ESTOQUE_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ESTOQUE_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ESTOQUE_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 6
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_ESTOQUE V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_TITULOS_ABERTO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TITULOS_ABERTO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TITULOS_ABERTO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 19
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_TITULOS_ABERTO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_EMPRESA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_EMPRESA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_EMPRESA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 10
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_EMPRESA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAX_CLIENTESENDERECOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAX_CLIENTESENDERECOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_CLIENTESENDERECOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 14
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAX_CLIENTESENDERECOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CLIENTESCREDITOS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CLIENTESCREDITOS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CLIENTESCREDITOS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 17
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CLIENTESCREDITOS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_COBRANCAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_COBRANCAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_COBRANCAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 9
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_COBRANCAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAX_PLANO_PGTO_CLIE_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAX_PLANO_PGTO_CLIE_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_PLANO_PGTO_CLIE_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 29
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAX_PLANO_PGTO_CLIE V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_MARCA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_MARCA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_MARCA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 23
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_MARCA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_SUPERVISOR_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_SUPERVISOR_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_SUPERVISOR_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 8
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_SUPERVISOR V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_VENDEDOR_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_VENDEDOR_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_VENDEDOR_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 7
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_VENDEDOR V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PROD_FILIAIS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROD_FILIAIS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROD_FILIAIS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 11
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PROD_FILIAIS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_REGIAO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_REGIAO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_REGIAO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 2
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_REGIAO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PRACA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRACA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRACA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 12
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PRACA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PLANO_PGTO_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PLANO_PGTO_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PLANO_PGTO_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 24
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PLANO_PGTO V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_NATUREZAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_NATUREZAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_NATUREZAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 37
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_NATUREZAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CODIGO_FISCAL_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CODIGO_FISCAL_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CODIGO_FISCAL_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 55
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CODIGO_FISCAL V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_CONTAS_BANCARIAS_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_CONTAS_BANCARIAS_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_CONTAS_BANCARIAS_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 39
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_CONTAS_BANCARIAS V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAX_CLIENTES_VENDEDOR_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAX_CLIENTES_VENDEDOR_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAX_CLIENTES_VENDEDOR_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 34
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAX_CLIENTES_VENDEDOR V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_TSICID_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_TSICID_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_TSICID_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 1
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_TSICID V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PROMOCOES_VLR
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROMOCOES_VLR
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROMOCOES_VLR
(
   MD5
 , MD5LINHA
 , CHAVE
 , CODPRECOPROM
 , DTINICIOVIGENCIA
 , DTFIMVIGENCIA
 , CODFILIAL
 , CODPROD
 , PRECOFIXO
 , NUMREGIAO
 , CODCLI
 , CODPRACA
 , UTILIZAPRECOFIXOREDE
 , UTILIZAPRECOFIXOFAMILIA
 , ORIGEMPED
) AS
   SELECT *
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 76 )
                     AS MD5
                , SNK_GET_MD5(
                               T.CODPRECOPROM || T.DTINICIOVIGENCIA || T.
                               DTFIMVIGENCIA || T.CODFILIAL || T.CODPROD ||
                               T.PRECOFIXO || T.NUMREGIAO || T.CODCLI || T.
                               CODPRACA || T.UTILIZAPRECOFIXOREDE || T.
                               UTILIZAPRECOFIXOFAMILIA || T.ORIGEMPED )
                     AS MD5LINHA
                , T.*
             FROM (SELECT LPAD( DES.NUPROMOCAO, 10, 0 ) || LPAD( PRO.CODPROD
                          , 10, 0 )
                             AS CHAVE
                        , NUPROMOCAO AS CODPRECOPROM
                        , DTINICIAL AS DTINICIOVIGENCIA
                        , DTFINAL AS DTFIMVIGENCIA
                        , CODEMP AS CODFILIAL
                        , CASE
                             WHEN PRO.CODPROD = 0 THEN NULL
                             ELSE PRO.CODPROD
                          END
                             AS CODPROD
                        , VLRVENDA AS PRECOFIXO
                        , CAST( DES.CODTAB AS VARCHAR( 10 ) ) AS NUMREGIAO
                        , CASE
                             WHEN DES.CODPARC = 0 THEN NULL
                             ELSE DES.CODPARC
                          END
                             AS CODCLI
                        , CAST( DES.CODTAB AS VARCHAR( 10 ) ) AS CODPRACA
                        , 'N' AS UTILIZAPRECOFIXOREDE
                        , 'N' AS UTILIZAPRECOFIXOFAMILIA
                        , 'F' AS ORIGEMPED
                     FROM TGFDES DES, TGFPRO PRO
                    WHERE DES.GRUPODESCPARC = '***************'
                      AND DES.GRUPODESCVEND = '***************'
                      AND DES.CODLOCAL = 0
                      AND DES.VLRVENDA > 0
                      AND NVL( DES.USADESCQTD, 'N' ) = 'N'
                      AND ( ( DES.CODPROD <> 0
                         AND DES.CODPROD = PRO.CODPROD )
                        OR ( DES.GRUPODESCPROD <> '***************'
                        AND DES.GRUPODESCPROD = PRO.GRUPODESCPROD )
                        OR ( DES.CODPROD = 0
                        AND PRO.CODPROD = 0
                        AND DES.CODPARC <> 0 ) )
                      AND TRUNC( SYSDATE ) BETWEEN DES.DTINICIAL
                                               AND DES.DTFINAL) T) T2
/

/*
NomeObjeto: VW_MAXIMA_PROMOCOES_VLR_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PROMOCOES_VLR_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PROMOCOES_VLR_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 76
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PROMOCOES_VLR V
               WHERE V.CHAVE = C.CHAVE
                 AND V.MD5LINHA = C.MD5)
/

/*
NomeObjeto: VW_MAXIMA_ORDEM_CARGA
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ORDEM_CARGA
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ORDEM_CARGA AS
   SELECT T2.*
     FROM (SELECT ( SELECT MD5
                     FROM AD_MAXIMA_INTEGRA
                    WHERE CHAVE = T.CHAVE
                      AND TIPO = 77 )
                     AS MD5
                , SNK_GET_MD5(
                               NUMCAR || TO_CHAR( T.DATAMON
                                                ,'YYYY-MM-DD HH24:MI:SS' ) ||
                               TO_CHAR
                               ( T.DTFAT, 'YYYY-MM-DD HH24:MI:SS' ) ||
                               TO_CHAR                                 (
                               T.DTSAIDA
                                                                        ,
                               'YYYY-MM-DD HH24:MI:SS' ) || ORIGEM_CAR ||
                               CODMOTORISTA || CODVEICULO || TOTPESO ||
                               VLTOTAL || NUMNOTAS )
                     AS MD5LINHA
                , T.*
             FROM (SELECT TO_CHAR(
                                   LPAD( ORD.CODEMP, 5, 0 ) || LPAD(
                                   ORD.ORDEMCARGA
                                                                   ,10
                                                                   ,0 ) )
                             AS CHAVE
                        , 'OC' || TO_CHAR(
                          LPAD             ( ORD.CODEMP, 5, 0 ) || LPAD(
                          ORD.ORDEMCARGA
                                                                       ,10
                                                                       ,0 ) )
                             AS NUMCAR
                        , ORD.DTPREVSAIDA AS DTSAIDA
                        , ORD.DTALTER AS DATAMON
                        , ( SELECT MIN( C.DTFATUR )
                             FROM TGFCAB C
                            WHERE C.CODEMP = ORD.CODEMP
                              AND C.ORDEMCARGA = ORD.ORDEMCARGA )
                             AS DTFAT
                        , 'ERP' AS ORIGEM_CAR
                        , ORD.CODPARCMOTORISTA AS CODMOTORISTA
                        , ORD.CODVEICULO
                        , ( SELECT SUM( C.PESOBRUTO )
                             FROM TGFCAB C
                            WHERE C.CODEMP = ORD.CODEMP
                              AND C.ORDEMCARGA = ORD.ORDEMCARGA )
                             AS TOTPESO
                        , ( SELECT SUM( C.PESOBRUTO )
                             FROM TGFCAB C
                            WHERE C.CODEMP = ORD.CODEMP
                              AND C.ORDEMCARGA = ORD.ORDEMCARGA )
                             AS TOTVOLUME
                        , ( SELECT SUM( C.VLRNOTA )
                             FROM TGFCAB C
                            WHERE C.CODEMP = ORD.CODEMP
                              AND C.ORDEMCARGA = ORD.ORDEMCARGA )
                             AS VLTOTAL
                        , ( SELECT COUNT( 1 )
                             FROM TGFCAB C
                            WHERE C.CODEMP = ORD.CODEMP
                              AND C.ORDEMCARGA = ORD.ORDEMCARGA )
                             AS NUMNOTAS
                        , ( SELECT NOMEREG
                             FROM TSIREG REG
                            WHERE REG.CODREG = ORD.CODREG )
                             AS DESTINO
                     FROM TGFORD ORD
                    WHERE EXISTS
                             (SELECT 1
                                FROM TGFCAB CAB
                               WHERE CAB.CODEMP = ORD.CODEMP
                                 AND CAB.ORDEMCARGA = ORD.ORDEMCARGA)) T) T2
/

/*
NomeObjeto: VW_MAXIMA_ORDEM_CARGA_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_ORDEM_CARGA_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_ORDEM_CARGA_DLT AS
   SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 77
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_ORDEM_CARGA V
               WHERE V.CHAVE = C.CHAVE)
/

/*
NomeObjeto: VW_MAXIMA_PRECOS_CLIENTES
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRECOS_CLIENTES
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRECOS_CLIENTES AS
SELECT T2.*
  , MD5LINHA AS HASH
FROM (  
  SELECT 
      ( SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 501 ) AS MD5
    , SNK_GET_MD5( T.CHAVE || T.CODFILIALNF || T.CODCLI || T.NUMREGIAO  ) AS MD5LINHA
    , T.*
  FROM (SELECT TO_CHAR( LPAD( PE.CODEMP, 5, 0 ) || LPAD( PE.CODPARC, 10, 0 ) || LPAD( PE.CODTAB, 5, 0 ) ) AS CHAVE
     , PE.CODEMP AS CODFILIALNF
     , PE.CODPARC AS CODCLI
     , PE.CODTAB AS NUMREGIAO
  FROM TGFPAEM PE, TSIEMP E, TGFPAR P
 WHERE P.CLIENTE = 'S'
   AND P.AD_MAXIMA_CLIENTE = 'S'
   AND E.AD_MAXIMA ='S'
   AND PE.CODEMP = E.CODEMP
   AND PE.CODPARC = P.CODPARC) T )T2

/

/*
NomeObjeto: VW_MAXIMA_PRECOS_CLIENTES_DLT
TipoObjeto: VIEW
NomeTabela: VW_MAXIMA_PRECOS_CLIENTES_DLT
Executar  : SEMPRE
*/ 

CREATE OR REPLACE VIEW VW_MAXIMA_PRECOS_CLIENTES_DLT AS   
SELECT C.MD5, C.ID
     FROM AD_MAXIMA_INTEGRA C
    WHERE C.TIPO = 501
      AND NOT EXISTS
             (SELECT 1
                FROM VW_MAXIMA_PRECOS_CLIENTES V
               WHERE V.CHAVE = C.CHAVE)

/

/*
NomeObjeto: STP_PERSONALIZACAO_MAX
TipoObjeto: PROCEDURE
NomeTabela: STP_PERSONALIZACAO_MAX
Executar  : SEMPRE
*/ 

DECLARE
   P_COUNT   NUMBER;
BEGIN
   SELECT COUNT( 1 )
     INTO P_COUNT
     FROM USER_SOURCE
    WHERE NAME = 'STP_PERSONALIZACAO_MAXIMA';

   IF ( P_COUNT > 0 ) THEN
      EXECUTE IMMEDIATE 'BEGIN STP_PERSONALIZACAO_MAXIMA; END;';
   END IF;
END;
/

