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

CREATE FUNCTION SNK_OBJETO_EXISTE( @valor VARCHAR(400) )
RETURNS int
AS
BEGIN
  RETURN CASE WHEN EXISTS( SELECT 1 FROM DBO.SYSOBJECTS WHERE NAME = @valor ) THEN 1 else 0 end
END
GO

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

CREATE FUNCTION SNK_COLUNA_EXISTE (@P_TABELA varchar(100), @P_COLUNA varchar(100))
RETURNS int
AS
BEGIN
   RETURN CASE WHEN EXISTS( SELECT 1
                            FROM SYS.COLUMNS C,
                                 SYS.OBJECTS T
                            WHERE T.NAME = @P_TABELA
                                AND C.NAME = @P_COLUNA
                                AND C.OBJECT_ID = T.OBJECT_ID
                                AND EXISTS (SELECT 1
                                          FROM SYS.SCHEMAS S
                                          WHERE S.NAME = 'SANKHYA'
                                            AND S.SCHEMA_ID = T.SCHEMA_ID)) THEN 1 ELSE 0 END
END
GO

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

CREATE TABLE TEIPCV_MAXIMA
(
ID BIGINT PRIMARY KEY,
NUFIN BIGINT,
CODVEND BIGINT,
TIPO CHAR(1),
CAIXAMX VARCHAR(40),
MOVIMENTOMX VARCHAR(40),
MENSAGEM VARCHAR(1000),
CODERRO BIGINT,
JSONREQUEST VARCHAR(4000)
);
GO

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

CREATE TABLE AD_PEDIDO_MAXIMA(
    NUNOTA INT PRIMARY KEY
  , AD_MAXIMA_NUMCAR  VARCHAR(50)
  , AD_MAXIMA_IDPEDIDO VARCHAR(20)
  , AD_MAXIMA_PEDIDO VARCHAR(50)
  , PESOBRUTO FLOAT
);
GO

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

CREATE TABLE AD_MAXIMA_MENSAGENS(
  CODMENSAGEM INT NOT NULL PRIMARY KEY
 ,CODVEND SMALLINT NOT NULL
 ,DTMENSAGEM DATETIME
 ,MENSAGEM TEXT
 ,STATUSMENSAGEM CHAR(1)
 ,CODUSU SMALLINT
); 
GO

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

CREATE TABLE AD_MAXIMA_PROCESSOS(
    ID INT NOT NULL,
  DESCRICAO VARCHAR(100),
  ID_ACAO INT
);
GO

/*
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
);
GO

/*
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
);
GO

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

BEGIN
	    EXECUTE('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('INSERT INTO AD_INSTANCIAS_MAXIMA (ID,DESCRICAO) SELECT 56 AS ID ,''Seções'' AS DESCRICAO FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM AD_INSTANCIAS_MAXIMA WHERE ID = 56)')
		EXECUTE('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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;
GO

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

/* TABELA CARREGAMENTOS POR VENDEDOR - PRONTA ENTREGA */
CREATE TABLE AD_MAXIMA_CARREGAMENTOS
(
    NUMCAR DECIMAL(10,0) NOT NULL
  , CODVEND SMALLINT NOT NULL
  , DTFECHAMENTO DATE
  , DTABERTURA DATE DEFAULT GETDATE()
)
GO

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

CREATE TABLE AD_MAXIMA_PRODFILIAL(
    CODPROD DECIMAL(10,0) NOT NULL
  , CODEMP INT NOT NULL
)
GO

/*
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 VARCHAR(200)
  , CODTAREFA INTEGER
  , NOME_VIEW VARCHAR(200)
  , ENDPOINT VARCHAR(200)
  , DELETAR CHAR(1) DEFAULT 'N' 
)
GO

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

CREATE TABLE AD_MAXIMA_INTEGRA(
    ID INTEGER IDENTITY (1, 1) NOT NULL
  , TIPO INTEGER NOT NULL
  , CHAVE VARCHAR(400) NOT NULL
  , MD5 CHAR(32)
  , DHALTER DATE
)
GO

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

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

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

CREATE TABLE AD_MAXIMALOG
(
ID                	BIGINT      IDENTITY(1,1)  NOT NULL,
TIPO_REGISTRO  		SMALLINT,
OPERACAO          	CHAR(1),
SENTIDO           	CHAR(1),
TIPO_RETORNO   		CHAR(1),
MENSAGEM          	NVARCHAR(max),
STACKTRACE    		NVARCHAR(max),
CHAVE             	VARCHAR(400),
DH_LOG            	DATETIME,
REQUEST 		  	VARCHAR(400), 
RESPONSE  		  	NVARCHAR(max),
BODY 			  	NVARCHAR(max),
TIPO_LOG 		  	SMALLINT
)
GO

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

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

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

ALTER TABLE TRIBUTACAO_MAXIMA ADD PERACRESCIMOFUNCEP FLOAT;
GO

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

ALTER TABLE TRIBUTACAO_MAXIMA ADD ALIQICMSFECP FLOAT;
GO

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

ALTER TABLE AD_MAXIMALOG ALTER COLUMN TIPO_REGISTRO DECIMAL(5,0)
GO

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

ALTER TABLE TSIEMP ADD AD_BROKER VARCHAR(1)
GO

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

ALTER TABLE TGFTAB ADD AD_NUMTABELA INT
GO

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

ALTER TABLE TGFTAB ADD AD_CODREPRESENTANTE INT
GO

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

ALTER TABLE TGFTAB ADD AD_CODESTABELECIMENTO INT
GO

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

ALTER TABLE TGFTIT ADD AD_COBRANCABROKER VARCHAR(1)
GO

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

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

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

ALTER TABLE TGFCAB ADD AD_NUMEROTABELA VARCHAR(20);
GO

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

ALTER TABLE TGFCAB ADD AD_CODIGOESTABELECIMENTO VARCHAR(20);
GO

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

ALTER TABLE TGFCPL ADD AD_MAXIMA_TELENTREGA VARCHAR(15)
GO

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

ALTER TABLE AD_MAXCONF ADD MAXRETORNOPARCIAL INT
GO

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

ALTER TABLE AD_MAXCONF ADD LOC_RETORNO_PARCIAL INT
GO

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

ALTER TABLE TGFCAB ADD AD_MAXIMA_PED_ORIGEM INT
GO

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

ALTER TABLE AD_MAXCONF ADD CODEMPBASE DECIMAL(10,0)
GO

/*
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);
GO

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

ALTER TABLE TGFFIN ADD AD_MAXIMA_IDFIN_CAIXA VARCHAR(100)
GO

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

ALTER TABLE TGFPAR ADD AD_CODTIPOPER DECIMAL(10,0)
GO

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

ALTER TABLE TGFPAR ADD AD_SERIENOTA CHAR(3)
GO

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

ALTER TABLE TGFCAB ADD AD_MAXIMA_IDPEDIDO VARCHAR(100)
GO

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

ALTER TABLE TGFITE ADD AD_MAXIMA_CODCOMBO DECIMAL(10,0)
GO

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

ALTER TABLE TGFMBC ADD AD_MAXIMA_IDMOVBCO VARCHAR(100)
GO

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

ALTER TABLE TGFCAI ADD AD_MAXIMA_IDCX VARCHAR(100)
GO

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

ALTER TABLE TGFFIN ADD AD_MAXIMA_IDFIN VARCHAR(100)
GO

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

ALTER TABLE TGFPRO ADD AD_MAXIMA_TIPO CHAR(1) --S – Inflamáveis, N – Normal, R - Refrigerado
GO

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

ALTER TABLE TGFVEN ADD AD_CODCTABCOINT DECIMAL(5,0)
GO

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

ALTER TABLE TGFCAB ADD AD_MAXIMA_NUMCAR VARCHAR(50)
GO

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

ALTER TABLE TGFORD ADD AD_MAXIMA_NUMCAR VARCHAR(50)
GO

/*
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
GO

/*
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
GO

GO

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

ALTER TABLE TGFFIN ADD AD_MAXIMA_RECEBE CHAR(1)
GO

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

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

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

ALTER TABLE TGFVEN ADD AD_MAXIMA_LOCAL DECIMAL(10,0) DEFAULT 0 NOT NULL
GO

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

ALTER TABLE TGFCAB ADD AD_MAXIMA_PEDIDO VARCHAR(50)
GO

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

ALTER TABLE TEIPCV_MAXIMA ADD DHLOG DATETIME;
GO

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

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

GO

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

ALTER TABLE TFPAFDT DROP 
  CONSTRAINT CKC_TIPREGISTRO_TFPAFDT
GO

/*
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'))
GO

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

ALTER TABLE TFPAFDT ADD GEOLOC VARCHAR(100)
GO

/*
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);
GO

/*
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);
GO

/*
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);
GO

/*
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);
GO

/*
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);
GO

/*
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);
GO

/*
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 );
GO

/*
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);
GO

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

ALTER TABLE AD_MAXIMA_CARREGAMENTOS ADD DTABERTURA DATETIME DEFAULT (GETDATE());
GO

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

ALTER TABLE AD_MAXCONF ADD TOP_RETORNO_DESCARGA DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD LOCAL_EMPRESA DECIMAL(10,0);
GO

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

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

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

ALTER TABLE AD_MAXCONF ADD TOP_NF_RETORNO  DECIMAL(5,0);
GO

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

ALTER TABLE AD_MAXCONF ADD TOP_ORCAMENTO   DECIMAL(5,0);
GO

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

ALTER TABLE AD_MAXCONF ADD TOP_ENTREGA_BALCAO   DECIMAL(5,0);
GO

GO

/*
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;
GO

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

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_COMPRAS_PENDENTE DECIMAL(5,0) DEFAULT 30 NOT NULL;
GO

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

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_PONTO DECIMAL(5,0) DEFAULT 1;
GO

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

ALTER TABLE AD_MAXCONF ADD MAXTOPTRANSFBANCARIA DECIMAL(5,0);
GO

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

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_CAIXAS DECIMAL(5,0) DEFAULT 2 NOT NULL;
GO

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

ALTER TABLE AD_MAXCONF ADD MODELOPRONTAENTREGA DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD MODELOPRONTAENTREGA_NOTA DECIMAL(10,0);
GO

/*
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;
GO

/*
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;
GO

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

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_ROTEIRIZAR DECIMAL(5,0) DEFAULT 1 NOT NULL;
GO

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

ALTER TABLE AD_MAXCONF ADD LOCAL_TRANSITO DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD MODELOREMESSA DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD MODELORETORNO DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD QTD_DIAS_CARREGAMENTO DECIMAL(5,0) DEFAULT 7 NOT NULL;
GO

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

ALTER TABLE AD_MAXCONF ADD TIT_CARTORIO DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD TIT_PROTESTO DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD NOTMODPREVENDA DECIMAL(10,0);
GO

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

ALTER TABLE AD_MAXCONF ADD USALIMITEFLEX CHAR(1) 
GO

/*
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;
GO

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

ALTER TABLE TGFTOP ADD AD_MAXIMAORIGEMPD VARCHAR(1)
GO

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

BEGIN   
   DECLARE @P_COUNT INT
	   SELECT @P_COUNT = COUNT(1) 
	   FROM INFORMATION_SCHEMA.COLUMNS 
	   WHERE TABLE_NAME = 'TGFPAR' AND COLUMN_NAME = 'AD_MAXIMA_CLIENTE'
   
   IF @P_COUNT = '0'    
    BEGIN   
		EXECUTE ('ALTER TABLE TGFPAR ADD AD_MAXIMA_CLIENTE CHAR(1)');
	   
	    EXECUTE('ALTER TABLE TGFPAR ADD AD_MAXIMA_FORNECEDOR VARCHAR(1)');
	
	    EXECUTE('ALTER TABLE TGFPAR ADD AD_MAXIMA_TRANSPORTADORA VARCHAR(1)');
	
	    EXECUTE('ALTER TABLE TGFPAR ADD AD_MAXIMA_MOTORISTA VARCHAR(1)');
	
	    EXECUTE('UPDATE TGFPAR SET AD_MAXIMA_CLIENTE = ''S'' WHERE AD_MAXIMA = ''S'' AND CLIENTE = ''S''');
	
	    EXECUTE('UPDATE TGFPAR SET AD_MAXIMA_FORNECEDOR = ''S'' WHERE AD_MAXIMA = ''S'' AND FORNECEDOR = ''S''');
	
	    EXECUTE('UPDATE TGFPAR SET AD_MAXIMA_TRANSPORTADORA = ''S'' WHERE AD_MAXIMA = ''S'' AND TRANSPORTADORA = ''S''');
	
	    EXECUTE('UPDATE TGFPAR SET AD_MAXIMA_MOTORISTA  = ''S'' WHERE AD_MAXIMA = ''S'' AND MOTORISTA = ''S''');
	
	    EXECUTE('ALTER TABLE TGFPAR DROP COLUMN AD_MAXIMA');
   END
   
   SELECT @P_COUNT = COUNT(1) 
	   FROM INFORMATION_SCHEMA.COLUMNS 
	   WHERE TABLE_NAME = 'TGFTOP' AND COLUMN_NAME = 'AD_MAXIMAORIGEMPD'
   
   IF @P_COUNT = '0'  
   BEGIN
	   EXECUTE('ALTER TABLE TGFTOP ADD AD_MAXIMAORIGEMPD VARCHAR(1)');
   END
END
GO

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

ALTER TABLE TGFCAB ADD AD_MAXIMA_STATUS SMALLINT
GO

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

ALTER TABLE TGFCAN ADD AD_MAXIMA_STATUS SMALLINT
GO

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

IF NOT EXISTS( SELECT 1 FROM TDDCAM WHERE NOMETAB = 'TGFGRU' AND NOMECAMPO = 'AD_MAXIMA') 
BEGIN
	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 Máxima?', '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', 'Não')

	INSERT INTO TDDOPC(NUCAMPO, 
	VALOR, OPCAO)  
	VALUES ((SELECT NUCAMPO FROM TDDCAM WHERE NOMETAB = 'TGFGRU' AND NOMECAMPO = 'AD_MAXIMA') , 
			'S', 'Sim')
END
GO

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

ALTER TABLE TGFTOP ADD AD_MAXIMA_TIPOVENDA INT
GO

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

ALTER TABLE TGFCAB ADD DH_MAXIMA_NUVEM DATETIME;
GO

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

ALTER TABLE TGFCAB ADD DH_MAXIMA_LANCAMENTO DATETIME;
GO

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

ALTER TABLE TRIBUTACAO_MAXIMA ADD CODGRUPOTRIBUT INTEGER;
GO

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

ALTER TABLE TRIBUTACAO_MAXIMA ADD PERDIFERIMENTOICMS FLOAT;
GO

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

ALTER TABLE TRIBUTACAO_MAXIMA ADD SITTRIBUTPF INT;
GO

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

BEGIN
    IF SANKHYA.SNK_COLUNA_EXISTE( 'TGFTOP', 'AD_ENVIARMAXIMA' ) = 0  BEGIN
      ALTER TABLE TGFTOP ADD AD_ENVIARMAXIMA CHAR(1) CONSTRAINT DF_TOP_ENVIARMAXIMA DEFAULT 'N' NOT NULL;
      EXEC('UPDATE TGFTOP SET AD_ENVIARMAXIMA = ''S'' WHERE AD_MAXIMAORIGEMPD IS NOT NULL');
    END;      
END;
GO

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

DROP TABLE AD_MAXIMA_PROGRESS_BAR;
GO

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

IF NOT EXISTS( SELECT 1 FROM TSIPAR WHERE CHAVE = 'TITTITPADRAOMAX') 
BEGIN
   INSERT INTO TSIPAR (CHAVE, DESCRICAO, CODUSU, TIPO, MODULO, CLASSE, ABA, LOGICO, INTEIRO)
   VALUES ('TITTITPADRAOMAX', 'Tipo de Título Padrão Máxima'
        , 0, 'T', 'E', 'Geral', 'Geral', 'N', NULL  );
END
GO

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

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

/*
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 )
GO

/*
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)
GO

/*
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)
GO

/*
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);
GO

/*
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 )
GO

/*
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 )
GO

/*
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 )
GO

/*
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)
GO

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

CREATE INDEX IDX_AD_MAXIMA_PEDIDO ON TGFCAB( AD_MAXIMA_PEDIDO );
GO

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

CREATE INDEX IDX_AD_MAXIMA_NUMCAR ON TGFCAB( AD_MAXIMA_NUMCAR );
GO

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

CREATE INDEX IDX_AD_MAXIMA_IDCX ON TGFCAI( AD_MAXIMA_IDCX );
GO

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

CREATE INDEX IDX_AD_MAXIMA_IDFIN ON TGFFIN( AD_MAXIMA_IDFIN )
GO

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

CREATE INDEX IDX_AD_MAXIMA_IDMOVBCO ON TGFMBC( AD_MAXIMA_IDMOVBCO );
GO

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

CREATE INDEX IDX_AD_MAXIMA_IDPEDIDO ON TGFCAB( AD_MAXIMA_IDPEDIDO);
GO

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

IF OBJECT_ID('GET_MAXIMA_NOTA', 'FN') IS NOT NULL
DROP FUNCTION GET_MAXIMA_NOTA
GO

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

CREATE FUNCTION SNK_GET_NOTA_MAXIMA( @P_NUNOTA INT )
  RETURNS INT AS
  BEGIN
  DECLARE
   /* 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),
  @V_NUNOTA INT
  SET @V_RESULT = 0;
    
   -- percorrendo as ligações pela TGFVAR
  DECLARE CR_LIGACAO CURSOR FAST_FORWARD FOR 
			SELECT DISTINCT V.NUNOTA 
			FROM TGFVAR V 
			WHERE V.NUNOTAORIG <> V.NUNOTA 
			AND V.NUNOTAORIG = @P_NUNOTA 
  OPEN CR_LIGACAO
  FETCH CR_LIGACAO INTO @V_NUNOTA
  WHILE @@FETCH_STATUS = 0
  BEGIN
    --obtendo o TIPMOV da ligação 
    SELECT @V_TIPMOV = MAX(TIPMOV)
    FROM TGFCAB
    WHERE NUNOTA = @V_NUNOTA;


    --se ligado com nota, seta o NUNOTA
    IF @V_TIPMOV = 'V'
      SET @V_RESULT = @V_NUNOTA; 
    ELSE IF @V_TIPMOV = 'P'-- se ligado com pedido, chama novamente recursivamente 
      SET @V_RESULT = SANKHYA.SNK_GET_NOTA_MAXIMA( @V_NUNOTA );
    
    --se achou a nota, retorna
    IF @V_RESULT <> 0 BEGIN
      CLOSE CR_LIGACAO
      DEALLOCATE CR_LIGACAO
      RETURN @V_RESULT;
    END;

    FETCH CR_LIGACAO INTO @V_NUNOTA
   END
   
   CLOSE CR_LIGACAO
   DEALLOCATE CR_LIGACAO

   RETURN @V_RESULT
END
GO

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

CREATE FUNCTION SNK_GET_PD_MAXIMA( @P_NUNOTA INT )
  RETURNS INT AS
  BEGIN
  DECLARE
   /* 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),
  @V_NUNOTA_ORIG INT
  SET @V_RESULT = 0;
    
   -- percorrendo as ligações pela TGFVAR
  DECLARE CR_LIGACAO CURSOR FAST_FORWARD FOR SELECT DISTINCT V.NUNOTA FROM TGFVAR V WHERE V.NUNOTAORIG = @P_NUNOTA 
  OPEN CR_LIGACAO
  FETCH CR_LIGACAO INTO @V_NUNOTA_ORIG
  WHILE @@FETCH_STATUS = 0
  BEGIN
    --obtendo o TIPMOV da ligação 
    SELECT @V_TIPMOV = MAX(TIPMOV)
    FROM TGFCAB
    WHERE NUNOTA = @V_NUNOTA_ORIG;


    --se ligado com nota, seta o NUNOTA
    IF @V_TIPMOV = 'P' BEGIN
      SET @V_RESULT = SANKHYA.SNK_GET_PD_MAXIMA( @V_NUNOTA_ORIG ); 
      --se não achou outro pedido
      IF @V_RESULT = 0
        SET @V_RESULT = @V_NUNOTA_ORIG;
    END  
    
    --se achou a nota, retorna
    IF @V_RESULT <> 0 BEGIN
      CLOSE CR_LIGACAO
      DEALLOCATE CR_LIGACAO
      RETURN @V_RESULT;
    END;
      
    FETCH CR_LIGACAO INTO @V_NUNOTA_ORIG
   END
   
   CLOSE CR_LIGACAO
   DEALLOCATE CR_LIGACAO

   RETURN @V_RESULT
END
GO

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

CREATE FUNCTION SNK_GET_MD5( @valor VARCHAR(MAX) ) 
RETURNS VARCHAR(32)  AS
BEGIN
	RETURN SUBSTRING( CONVERT( CHAR(32), HashBytes('MD5',  @valor ) , 1 ), 3 , 32 )
END
GO

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

CREATE FUNCTION SNK_GET_CUSTO(@CAMPO            VARCHAR(10),
                             @CODPROD          INT,
                             @CODEMP           INT,
                             @CODLOCAL         INT,
                             @CONTROLE         VARCHAR(100),
                             @DATA             DATETIME,
                             @CUSTOPOREMP      CHAR(1),
                             @CUSTOPORLOCAL    CHAR(1),
                             @CUSTOPORCONTROLE CHAR(1))
RETURNS FLOAT
AS  
BEGIN  
 DECLARE @RESULT FLOAT  

 SELECT @RESULT = MAX(CASE WHEN @CAMPO = 'CUSGER' THEN CUSGER   
                       WHEN @CAMPO = 'CUSREP' THEN CUSREP 
                       WHEN @CAMPO = 'CUSVARIAVE' THEN CUSVARIAVEL 
                       WHEN @CAMPO = 'CUSMED' THEN CUSMED 
                       WHEN @CAMPO = 'CUSSEMICM' THEN CUSSEMICM 
                       WHEN @CAMPO = 'CUSMEDICM' THEN CUSMEDICM 
                       WHEN @CAMPO = 'ENTRADACOM' THEN ENTRADACOMICMS 
                       WHEN @CAMPO = 'ENTRADASEM' THEN ENTRADASEMICMS 
                  ELSE 0 END )  
 FROM TGFCUS C (nolock)
 WHERE C.CODPROD = @CODPROD    
   AND C.CODEMP = SANKHYA.GET_EMPRESA_CUSTO( @CUSTOPOREMP, C.CODEMP, @CODEMP )    
   AND C.CODLOCAL = SANKHYA.GET_LOCAL_CUSTO( @CUSTOPORLOCAL, C.CODLOCAL, @CODLOCAL )    
   AND C.CONTROLE = SANKHYA.GET_CONTROLE_CUSTO( @CUSTOPORCONTROLE, C.CONTROLE, @CONTROLE )    
   AND C.DTATUAL =  (SELECT MAX(CN.DTATUAL)
                     FROM TGFCUS CN (nolock)   
                     WHERE CN.CODPROD = @CODPROD
                       AND CN.CODEMP = SANKHYA.GET_EMPRESA_CUSTO( @CUSTOPOREMP,CN.CODEMP, @CODEMP)
                       AND CN.CODLOCAL = SANKHYA.GET_LOCAL_CUSTO( @CUSTOPORLOCAL,CN.CODLOCAL, @CODLOCAL)
                       AND CN.CONTROLE = SANKHYA.GET_CONTROLE_CUSTO( @CUSTOPORCONTROLE,CN.CONTROLE, @CONTROLE)
                       AND CN.DTATUAL <= @DATA )
 RETURN @RESULT
END
GO

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

CREATE FUNCTION SNK_GET_PRECO(
    @NUTAB    INT,
    @CODPROD  INT,
  @DTVIGOR DATETIME) RETURNS FLOAT
AS
BEGIN
    DECLARE
        @COUNT            INT,
        @TIPO             CHAR,
        @VALOR       	  FLOAT,
        @TROCA            INT,
   		@CODGRUPOPROD     INT,
	    @COMVEND          FLOAT,
	    @COMGER           FLOAT,
	    @MARGLUCRO        FLOAT,
	    @ESTMAX           FLOAT,
        @PERCEN      FLOAT,
        @MULTIP      FLOAT,
        @DECVLR      INT,
        @CODTAB      INT,
        @CODTABORIG  INT,
        @CUSFIX      FLOAT,
   		@PERCGRUPO   FLOAT,
   		@DTVIGORAUX  DATE,
        @SEMPRE      CHAR,
        @ATIVO       char(1),
    @UTILZADECCUSTO  CHAR(1),
    @CUSTODEC        INT,
    @PRECO      FLOAT
    BEGIN
        SET @PRECO = 0

    SET @CUSTODEC = SANKHYA .GET_TSIPAR_INTEIRO('CUSTODEC')

        SELECT @COUNT = COUNT(1), @DECVLR = MAX(DECVLR)
        FROM TGFPRO (NOLOCK)
        WHERE CODPROD = @CODPROD
        AND CODPROD <> 0

        IF ((@COUNT IS NULL) OR (@COUNT = 0))
            RETURN @PRECO

        SELECT @ATIVO = ATIVO
           /* ,@CODTABORIG = ISNULL(T.CODTABORIG, T.CODTAB) --ESTA LINHA FAZ PARTE DO TRECHO COMENTADO
              
              ,@CODTAB  = T.CODTAB  --ESTA LINHA FAZ PARTE DO TRECHO COMENTADO */        
                FROM TGFNTA N (NOLOCK), TGFTAB T (NOLOCK)
        WHERE T.NUTAB = @NUTAB
        AND T.CODTAB = N.CODTAB

        IF (@ATIVO = 'N')
            RETURN @PRECO

        IF (@DECVLR IS NULL)
            SET @DECVLR = 2

        IF (@DTVIGOR IS NULL)
            SET @DTVIGOR = GETDATE()

        SET @SEMPRE = 'S'
        SET @VALOR = 0
        SET @MULTIP = 0

-- AO COMENTAR/DESCOMENTAR O TRECHO ABAIXO, NAO ESQUEÇA DE COMENTAR/DESCOMENTAR AS 2 LINHAS DO SELECT LOGO ACIMA
-- COM ESTE TECHO, NÃO PODE EXCLUIR PRODUTO, TEM QUE INCLUIR PREÇO ZERO. SE APAGAR UM PREÇO, O PREÇO ANTERIOR VOLTA.
-- SEM ISTO, TODOS OSPRODUTOS DE TABORIG=TAB TEM QUE SER COPIADOS PARA A NOVA TABELA. ISTO PERMITE EXCLUIR PRODUTOS, JÁ QUE O ÚLTIMO NÃO SERÁ APRESENTADO.         
/*
    IF @CODTABORIG = @CODTAB AND @CODTAB <> 0 
        IF NOT EXISTS(SELECT 1            
                   FROM TGFEXC E
                  WHERE E.NUTAB = @NUTAB
                    AND E.CODPROD = @CODPROD)      
          SELECT @NUTAB = ISNULL(MAX (M.NUTAB), -999999)        
          FROM TGFTAB M, TGFEXC E
          WHERE M.DTVIGOR <= @DTVIGOR
          AND M.CODTAB = @CODTAB
          AND E.CODPROD = @CODPROD
          AND E.NUTAB = M.NUTAB
*/

        WHILE (@SEMPRE = 'S')
            BEGIN
                SELECT 
          @PERCEN = isnull(PERCENTUAL,0),
          @CODTABORIG = ISNULL(CODTABORIG, CODTAB),       
          @CODTAB = CODTAB,
          @UTILZADECCUSTO = UTILIZADECCUSTO
        FROM TGFTAB (NOLOCK)
        WHERE NUTAB   = @NUTAB

        IF @UTILZADECCUSTO = 'S'
          IF @CUSTODEC <> 0 
            SET @DECVLR = @CUSTODEC
          ELSE
            SET @DECVLR = 2

                SELECT @TIPO = MAX(E.TIPO), 
                @VALOR = MAX(E.VLRVENDA)
                FROM TGFEXC E (NOLOCK)
                WHERE E.NUTAB = @NUTAB
                AND E.CODPROD  = @CODPROD


                IF (@TIPO IS NOT NULL)
                    BEGIN
                        IF ((@TIPO = 'P') AND (@CODTABORIG <> @CODTAB))
                            BEGIN
                                SET @MULTIP = @MULTIP + (@VALOR / 100.0000)

                                SELECT @NUTAB = MAX(M.NUTAB)
                                FROM TGFTAB M (NOLOCK) , TGFEXC E (NOLOCK)
                                WHERE E.NUTAB = M.NUTAB
                                AND M.CODTAB = @CODTABORIG
                AND E.CODPROD = @CODPROD
                AND M.DTVIGOR = (  SELECT MAX(M2.DTVIGOR)
                           FROM TGFTAB M2 (NOLOCK) , TGFEXC E2 (NOLOCK)
                           WHERE E2.NUTAB = M2.NUTAB
                           AND M2.CODTAB = @CODTABORIG
                           AND E2.CODPROD = @CODPROD
                           AND M2.DTVIGOR <= @DTVIGOR
                        )
                                
                                
                                IF (@NUTAB IS NULL)
                                    BEGIN
                                        SELECT @NUTAB = MAX(M.NUTAB)
                                        FROM TGFTAB M (NOLOCK)
                                        WHERE M.DTVIGOR <= @DTVIGOR
                                        AND M.CODTAB = @CODTABORIG
                    AND M.DTVIGOR = (  SELECT MAX(T.DTVIGOR)
                               FROM TGFTAB T
                               WHERE T.CODTAB = @CODTABORIG
                               AND T.DTVIGOR <= @DTVIGOR )

                                        IF (@NUTAB IS NULL)
                                          BEGIN
                                            SET @PRECO = 0
                                            SET @SEMPRE = 'N'
                                          END
                                    END
                            END
                        ELSE
                            BEGIN
                                IF (@MULTIP <> 0)
                                    SET @PRECO = ROUND(@VALOR + (@VALOR * @MULTIP),@DECVLR)
                                ELSE
                                    SET @PRECO = ROUND(@VALOR, @DECVLR)
                                
                                SET @SEMPRE = 'N'
                                 /*PRINT ''SAIU NO ACHOU'' */
                            END
                    END
                ELSE IF (@CODTAB = 0)
                    BEGIN
                         /*PRINT ''TAB 0''  */
                        SELECT @NUTAB = MAX(M.NUTAB)
            FROM TGFTAB M (NOLOCK) , TGFEXC E (NOLOCK)
            WHERE E.NUTAB = M.NUTAB
            AND M.CODTAB = 0
            AND E.CODPROD = @CODPROD
            AND M.DTVIGOR = (  SELECT MAX(M2.DTVIGOR)
                       FROM TGFTAB M2 (NOLOCK) , TGFEXC E2 (NOLOCK)
                       WHERE E2.NUTAB = M2.NUTAB
                       AND M2.CODTAB = 0
                       AND E2.CODPROD = @CODPROD
                       AND M2.DTVIGOR <= @DTVIGOR
                    )

                        IF (@NUTAB IS NULL)
                          BEGIN
                            SET @PRECO = 0
                            SET @SEMPRE = 'N'
                          END
                    END
                ELSE IF (@CODTABORIG = @CODTAB)
                    BEGIN
                        SET @PRECO = 0
                        SET @SEMPRE = 'N'
                         /*PRINT ''TAB IGUAIS''  */
                    END
                ELSE
                    BEGIN
                        SET @MULTIP = @MULTIP + (@PERCEN / 100.0000)
                    
                        SELECT @NUTAB = MAX(M.NUTAB)
            FROM TGFTAB M (NOLOCK) , TGFEXC E (NOLOCK)
            WHERE E.NUTAB = M.NUTAB
            AND M.CODTAB = @CODTABORIG
            AND E.CODPROD = @CODPROD
            AND M.DTVIGOR = (  SELECT MAX(M2.DTVIGOR)
                       FROM TGFTAB M2 (NOLOCK) , TGFEXC E2 (NOLOCK)
                       WHERE E2.NUTAB = M2.NUTAB
                       AND M2.CODTAB = @CODTABORIG
                       AND E2.CODPROD = @CODPROD
                       AND M2.DTVIGOR <= @DTVIGOR
                    )
                        
                        IF (@NUTAB IS NULL)
                            BEGIN
                                SELECT @NUTAB = MAX(M.NUTAB)
                                FROM TGFTAB M (NOLOCK)
                                WHERE M.DTVIGOR <= @DTVIGOR
                                AND M.CODTAB = @CODTABORIG
                AND M.DTVIGOR = (  SELECT MAX(T.DTVIGOR)
                           FROM TGFTAB T
                           WHERE T.CODTAB = @CODTABORIG
                           AND T.DTVIGOR <= @DTVIGOR )
                                
                                IF (@NUTAB IS NULL)
                                  BEGIN
                                      SET @PRECO = 0
                                      SET @SEMPRE = 'N'
                                  END
                                                      ELSE
                                                        BEGIN
                                    
                  SELECT @CODTABORIG = ISNULL(CODTABORIG, CODTAB),
                                    @CODTAB = CODTAB
                                    FROM TGFTAB (NOLOCK)
                                    WHERE NUTAB = @NUTAB
                                    
                  IF (@CODTABORIG = @CODTAB)                                    
                                      
                    SELECT @NUTAB = MAX(M.NUTAB)
                    FROM TGFTAB M (NOLOCK) , TGFEXC E (NOLOCK)
                    WHERE E.NUTAB = M.NUTAB
                    AND M.CODTAB = @CODTABORIG
                    AND E.CODPROD = @CODPROD
                    AND M.DTVIGOR = (  SELECT MAX(M2.DTVIGOR)
                               FROM TGFTAB M2 (NOLOCK) , TGFEXC E2 (NOLOCK)
                               WHERE E2.NUTAB = M2.NUTAB
                               AND M2.CODTAB = @CODTABORIG
                               AND E2.CODPROD = @CODPROD
                               AND M2.DTVIGOR <= @DTVIGOR
                            )
                                      
                    IF (@NUTAB IS NULL)
                    BEGIN
                    SET @PRECO = 0
                    SET @SEMPRE = 'N'
                    END
                                    END
                            END
                            ELSE 
                            BEGIN
                            SET @MULTIP = 0
                            END
                    END
            END
      RETURN @PRECO
        END
END;
GO

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

CREATE FUNCTION SNK_GET_PROXIMO_CODIGO(
	@P_ARQUIVO VARCHAR(100), 
	@P_CODEMP INT, 
	@P_TABELA VARCHAR(100), 
	@P_CAMPO VARCHAR(100) 
	)
RETURNS FLOAT 
AS
BEGIN
	DECLARE
	@P_ULTCOD INT,
 	@P_DSYNC INT
 	
   	SELECT @P_DSYNC = COUNT(1) FROM TSDPAR,
   	
 STP_KEYGEN_TGFNUM(@P_ARQUIVO , @P_CODEMP , @P_TABELA , @P_CAMPO , @P_DSYNC , @P_ULTCOD )
  RETURN @P_ULTCOD
END
GO

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

IF NOT EXISTS( SELECT 1 FROM TSISNK WHERE OBJETO = 'STP_OBTEM_PRECO2')
BEGIN
	IF SANKHYA.SNK_OBJETO_EXISTE('STP_OBTEM_PRECO2') > 0 
	  DROP PROCEDURE STP_OBTEM_PRECO2;

	EXECUTE('
	CREATE PROCEDURE STP_OBTEM_PRECO2(
		@NUTAB    INT,
		@CODPROD  INT,
		@DTVIGOR DATE,
		@PRECO    FLOAT OUT)
	AS
		BEGIN
		  SET @PRECO = SANKHYA.SNK_GET_PRECO( @NUTAB, @CODPROD, @DTVIGOR )
		END
	')
END
GO

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

CREATE PROCEDURE STP_TRIBUTACAO_MAXIMA AS
BEGIN
  DECLARE
    @QTDTOTALPARC   INT,
    @V_TIPOVENDA    INT;
   /* LIMPANDO A TABELA DE TRIBUTAÇÃO MÁXIMA */
   EXECUTE ('TRUNCATE TABLE TRIBUTACAO_MAXIMA');

   SELECT @V_TIPOVENDA = CASE WHEN COUNT(1) > 0 THEN 14 ELSE 1 END
   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 TRIBUTAÇÃO PADRÃO ( SEM RESTRIÇÃO ) */
   INSERT INTO TRIBUTACAO_MAXIMA
   (    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 DISTINCT 
                   CASE WHEN ISNULL( CODEMP, 0 ) = 0 THEN (SELECT ISNULL(MIN(CODEMPBASE),1) FROM AD_MAXCONF) ELSE CODEMP END AS CODEMP
                 , ISNULL( CODPROD, 0 ) AS CODPROD
                 , CASE WHEN ISNULL( CODFILIALNF, 0 ) = 0 THEN 1 ELSE CODFILIALNF END AS CODFILIALNF
                 , ISNULL( UFDESTINO, ' ') AS UFDESTINO
                 , ISNULL( CODOPER, 0 ) AS CODOPER
                 , ISNULL( CODCLI, 0 ) AS CODCLI
                 , ISNULL( AGREGARIPICALCULOST, 'N') AS AGREGARIPICALCULOST
                 , ISNULL( ALIQICMS1, 0 ) AS ALIQICMS1
                 , ISNULL( ALIQICMS1FONTE, 0 ) AS ALIQICMS1FONTE
                 , ISNULL( ALIQICMS2, 0 ) AS ALIQICMS2
                 , ISNULL( ALIQICMS2FONTE, 0 ) AS ALIQICMS2FONTE
                 , ISNULL( CODICM, 0 ) AS CODICM
                 , ISNULL( CODICMPF, 0 ) AS CODICMPF
                 , ISNULL( CODICMPRODRURAL, 0 ) AS CODICMPRODRURAL
                 , ISNULL( CODICMTAB, 0 ) AS CODICMTAB
                 , ISNULL( CODICMTABPF, 0 ) AS CODICMTABPF
                 , ISNULL( IVA, 0 ) AS IVA
                 , ISNULL( IVAFONTE, 0 ) AS IVAFONTE
                 , ISNULL( MOSTRARPVENDASEMIPI, 'N') AS MOSTRARPVENDASEMIPI
                 , ISNULL( MOSTRARPVENDASEMST, 'N') AS MOSTRARPVENDASEMST
                 , ISNULL( OBS, ' ') AS OBS
                 , ISNULL( PAUTA, 0 ) AS PAUTA
                 , ISNULL( PERACRESCIMOPF, 0 ) AS PERACRESCIMOPF
                 , ISNULL( PERBASEREDNRPA, 0 ) AS PERBASEREDNRPA
                 , ISNULL( PERCACRESICMSPF_PI, 0 ) AS PERCACRESICMSPF_PI
                 , ISNULL( PERCBASERED, 0 ) AS PERCBASERED
                 , ISNULL( CONSUMIDOR, 'N') AS CONSUMIDOR
                 , ISNULL( TIPOSN, 0 ) AS TIPOSN
                 , ISNULL( PERCBASEREDST, 0 ) AS PERCBASEREDST
                 , ISNULL( PERCBASEREDSTFONTE, 0 ) AS PERCBASEREDSTFONTE
                 , ISNULL( PERCBASESTRJ, 0 ) AS PERCBASESTRJ
                 , ISNULL( PERCDESCCOFINS, 0 ) AS PERCDESCCOFINS
                 , ISNULL( PERCDESCPIS, 0 ) AS PERCDESCPIS
                 , ISNULL( PERDESCICMISENCAO, 0 ) AS PERDESCICMISENCAO
                 , ISNULL( PERDESCPISSUFRAMA, 0 ) AS PERDESCPISSUFRAMA
                 , ISNULL( PERDESCREPASSE, 0 ) AS PERDESCREPASSE
                 , ISNULL( PERDESCSUFRAMA, 0 ) AS PERDESCSUFRAMA
                 , ISNULL( RIOLOGISENTOST, 0 ) AS RIOLOGISENTOST
                 , ISNULL( SITTRIBUT, 0 ) AS SITTRIBUT
                 , ISNULL( SITTRIBUTPF, SITTRIBUT ) AS SITTRIBUTPF
                 , ISNULL( TIPOCALCULOGNRE, 'P') AS TIPOCALCULOGNRE
                 , ISNULL( TV9ISENTOST, 0 ) AS TV9ISENTOST
                 , ISNULL( USAVALORULTENTBASEST, 'N') AS USAVALORULTENTBASEST
                 , ISNULL( USAVALORULTENTBASEST2, 'N') AS USAVALORULTENTBASEST2
                 , ISNULL( USAVLULTENTMEDIOBASEST, 'N') AS USAVLULTENTMEDIOBASEST
                 , ISNULL( UTILIZAPERCBASEREDPF, 0 ) AS UTILIZAPERCBASEREDPF
                 , ISNULL( CODFISCALVENDAPRONTAENT, 0 ) AS CODFISCALVENDAPRONTAENT
                 , ISNULL( CODFISCALVENDAPRONTAENTINTER, 0 ) AS CODFISCALVENDAPRONTAENTINTER
                 , ISNULL( CODFISCALBONIFIC, 0 ) AS CODFISCALBONIFIC
                 , ISNULL( CODFISCALBONIFICINTER, 0 ) AS CODFISCALBONIFICINTER
                 , ISNULL( PRIORIDADE, 0 ) AS PRIORIDADE
                 , ISNULL( PERCBASEREDCONSUMIDOR, 0 ) AS PERCBASEREDCONSUMIDOR
                 , ISNULL( PERCREDPVENDASIMPLESNAC, 0 ) AS PERCREDPVENDASIMPLESNAC
                 , ISNULL( PERDIFERIMENTOICMS, 0 ) AS PERDIFERIMENTOICMS
                 , ISNULL( CODGRUPOTRIBUT, 0 ) AS CODGRUPOTRIBUT
                 , ISNULL( ALIQICMSFECP, 0 ) AS ALIQICMSFECP
                 , ISNULL( 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) )
                                 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 --Parâmetro IPIINCICMS                                       
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS1 --Aliquota de ST Interno
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS1FONTE --Aliquota de ST Interno
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS2 --Aliquota de ST Externo
                                       , ISNULL( 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
                                       , ISNULL( ICM.CUSCOMICMSBASEST, 'N')
                                            AS USAVALORULTENTBASEST
                                       , ISNULL( 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
                                                   ISNULL( (   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;
                      
   /* INSERINDO TRIBUTAÇÃO PADRÃO ( COM RESTRIÇÃO ) */
   INSERT INTO TRIBUTACAO_MAXIMA
   (    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 DISTINCT
                   CASE WHEN ISNULL( CODEMP, 0 ) = 0 THEN (SELECT ISNULL(MIN(CODEMPBASE),1) FROM AD_MAXCONF) ELSE CODEMP END AS CODEMP
                 , ISNULL( CODPROD, 0 ) AS CODPROD
                 , CASE WHEN ISNULL( CODFILIALNF, 0 ) = 0 THEN 1 ELSE CODFILIALNF END AS CODFILIALNF
                 , ISNULL( UFDESTINO, ' ') AS UFDESTINO
                 , ISNULL( CODOPER, 0 ) AS CODOPER
                 , ISNULL( CODCLI, 0 ) AS CODCLI
                 , ISNULL( AGREGARIPICALCULOST, 'N') AS AGREGARIPICALCULOST
                 , ISNULL( ALIQICMS1, 0 ) AS ALIQICMS1
                 , ISNULL( ALIQICMS1FONTE, 0 ) AS ALIQICMS1FONTE
                 , ISNULL( ALIQICMS2, 0 ) AS ALIQICMS2
                 , ISNULL( ALIQICMS2FONTE, 0 ) AS ALIQICMS2FONTE
                 , ISNULL( CODICM, 0 ) AS CODICM
                 , ISNULL( CODICMPF, 0 ) AS CODICMPF
                 , ISNULL( CODICMPRODRURAL, 0 ) AS CODICMPRODRURAL
                 , ISNULL( CODICMTAB, 0 ) AS CODICMTAB
                 , ISNULL( CODICMTABPF, 0 ) AS CODICMTABPF
                 , ISNULL( IVA, 0 ) AS IVA
                 , ISNULL( IVAFONTE, 0 ) AS IVAFONTE
                 , ISNULL( MOSTRARPVENDASEMIPI, 'N') AS MOSTRARPVENDASEMIPI
                 , ISNULL( MOSTRARPVENDASEMST, 'N') AS MOSTRARPVENDASEMST
                 , ISNULL( OBS, ' ') AS OBS
                 , ISNULL( PAUTA, 0 ) AS PAUTA
                 , ISNULL( PERACRESCIMOPF, 0 ) AS PERACRESCIMOPF
                 , ISNULL( PERBASEREDNRPA, 0 ) AS PERBASEREDNRPA
                 , ISNULL( PERCACRESICMSPF_PI, 0 ) AS PERCACRESICMSPF_PI
                 , ISNULL( PERCBASERED, 0 ) AS PERCBASERED
                 , ISNULL( CONSUMIDOR, 'N') AS CONSUMIDOR
                 , ISNULL( TIPOSN, 0 ) AS TIPOSN
                 , ISNULL( PERCBASEREDST, 0 ) AS PERCBASEREDST
                 , ISNULL( PERCBASEREDSTFONTE, 0 ) AS PERCBASEREDSTFONTE
                 , ISNULL( PERCBASESTRJ, 0 ) AS PERCBASESTRJ
                 , ISNULL( PERCDESCCOFINS, 0 ) AS PERCDESCCOFINS
                 , ISNULL( PERCDESCPIS, 0 ) AS PERCDESCPIS
                 , ISNULL( PERDESCICMISENCAO, 0 ) AS PERDESCICMISENCAO
                 , ISNULL( PERDESCPISSUFRAMA, 0 ) AS PERDESCPISSUFRAMA
                 , ISNULL( PERDESCREPASSE, 0 ) AS PERDESCREPASSE
                 , ISNULL( PERDESCSUFRAMA, 0 ) AS PERDESCSUFRAMA
                 , ISNULL( RIOLOGISENTOST, 0 ) AS RIOLOGISENTOST
                 , ISNULL( SITTRIBUT, 0 ) AS SITTRIBUT
                 , ISNULL( SITTRIBUTPF, SITTRIBUT ) AS SITTRIBUTPF
                 , ISNULL( TIPOCALCULOGNRE, 'P') AS TIPOCALCULOGNRE
                 , ISNULL( TV9ISENTOST, 0 ) AS TV9ISENTOST
                 , ISNULL( USAVALORULTENTBASEST, 'N') AS USAVALORULTENTBASEST
                 , ISNULL( USAVALORULTENTBASEST2, 'N') AS USAVALORULTENTBASEST2
                 , ISNULL( USAVLULTENTMEDIOBASEST, 'N')
                      AS USAVLULTENTMEDIOBASEST
                 , ISNULL( UTILIZAPERCBASEREDPF, 0 ) AS UTILIZAPERCBASEREDPF
                 , ISNULL( CODFISCALVENDAPRONTAENT, 0 ) AS CODFISCALVENDAPRONTAENT
                 , ISNULL( CODFISCALVENDAPRONTAENTINTER, 0 ) AS CODFISCALVENDAPRONTAENTINTER
                 , ISNULL( CODFISCALBONIFIC, 0 ) AS CODFISCALBONIFIC
                 , ISNULL( CODFISCALBONIFICINTER, 0 ) AS CODFISCALBONIFICINTER
                 , ISNULL( PRIORIDADE, 0 ) AS PRIORIDADE
                 , ISNULL( PERCBASEREDCONSUMIDOR, 0 ) AS PERCBASEREDCONSUMIDOR
                 , ISNULL( PERCREDPVENDASIMPLESNAC, 0 ) AS PERCREDPVENDASIMPLESNAC
                 , ISNULL( PERDIFERIMENTOICMS, 0 ) AS PERDIFERIMENTOICMS
                 , ISNULL( CODGRUPOTRIBUT, 0 ) AS CODGRUPOTRIBUT
                 , ISNULL( ALIQICMSFECP, 0 ) AS ALIQICMSFECP
                 , ISNULL( 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) )
                                 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 --Parâmetro IPIINCICMS
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS1 --Aliquota de ST Interno
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS1FONTE --Aliquota de ST Interno
                                       , ISNULL( ALIQSUBTRIB, 0 ) AS ALIQICMS2 --Aliquota de ST Externo
                                       , ISNULL( ALIQSUBTRIB, 0 ) 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 
                                          ISNULL(( 
                                                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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD')
                                                                                     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 ISNULL(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
                                       , ISNULL( ICM.CUSCOMICMSBASEST, 'N')
                                            AS USAVALORULTENTBASEST
                                       , ISNULL( 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
                                                   ISNULL( (   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; 
END
GO

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

CREATE PROCEDURE STP_GERALOG_BD (
   @V_TIPO_REGISTRO  SMALLINT
  ,@V_OPERACAO          VARCHAR(1)
  ,@V_CHAVE             VARCHAR(400)
  ,@V_MENSAGEM          NVARCHAR(MAX)
  ,@V_REQUEST           NVARCHAR(MAX)
  ,@V_RESPONSE        	NVARCHAR(MAX)
  ,@V_BODY          	NVARCHAR(MAX)
  ,@V_TIPO_LOG			INT
  ,@V_STACKTRACE		NVARCHAR(MAX)
  ) 
AS 
BEGIN
	DECLARE @V_MENORDATALOG DATE;

	BEGIN TRAN
       
	   --BUSCANDO MENOR DATA NO LOG
	   SELECT @V_MENORDATALOG = SANKHYA.SNK_TRUNC_DATE( ISNULL( MIN(DH_LOG), GETDATE() ), 'DD') 
	   FROM AD_MAXIMALOG;
   
	   --MANTÉM NO LOG APENAS LINHAS COM ATÉ 15 DIAS
	   IF @V_MENORDATALOG < SANKHYA.SNK_TRUNC_DATE(GETDATE() - 15, 'DD' ) 
		 --EXCLUINDO LINHAS ANTIGAS 
		 DELETE FROM AD_MAXIMALOG WHERE SANKHYA.SNK_TRUNC_DATE(DH_LOG, 'DD') < SANKHYA.SNK_TRUNC_DATE(GETDATE() - 15, 'DD' ) 

	  INSERT INTO AD_MAXIMALOG
				  (TIPO_REGISTRO 
				  ,OPERACAO
				  ,CHAVE 
				  ,DH_LOG
				  ,MENSAGEM
				  ,REQUEST
				  ,RESPONSE
				  ,BODY
				  ,TIPO_LOG
				  ,STACKTRACE) 
	  VALUES      (@V_TIPO_REGISTRO 
				  ,@V_OPERACAO
				  ,@V_CHAVE
				  ,GETDATE()
				  ,@V_MENSAGEM
				  ,@V_REQUEST
				  ,@V_RESPONSE
				  ,@V_BODY
				  ,@V_TIPO_LOG
				  ,@V_STACKTRACE); 
  COMMIT; 
END
GO

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

IF OBJECT_ID('STP_SALVAERRO_BD', 'P') IS NOT NULL
  DROP PROCEDURE STP_SALVAERRO_BD;
GO

CREATE PROCEDURE STP_SALVAERRO_BD (
@P_NUFIN FLOAT,
@P_CODVEND FLOAT,
@P_TIPO CHAR,
@P_CAIXAMX VARCHAR(4000),
@P_MOVIMENTOMX VARCHAR(4000),
@P_MENSAGEM VARCHAR(4000),
@P_CODERRO FLOAT,
@P_JSONREQUEST VARCHAR(4000)
   ) 
AS  
BEGIN
   DECLARE @V_MENORDATALOG DATE;

	BEGIN TRAN
       
	   --BUSCANDO MENOR DATA NO LOG
	   SELECT @V_MENORDATALOG = SANKHYA.SNK_TRUNC_DATE( ISNULL( MIN(DHLOG), GETDATE() ), 'DD') 
	   FROM TEIPCV_MAXIMA;
   
	   --MANTÉM NO LOG APENAS LINHAS COM ATÉ 15 DIAS
	   IF @V_MENORDATALOG < SANKHYA.SNK_TRUNC_DATE(GETDATE() - 15, 'DD' ) 
		 --EXCLUINDO LINHAS ANTIGAS 
		 DELETE FROM TEIPCV_MAXIMA 
		 WHERE DHLOG IS NULL OR SANKHYA.SNK_TRUNC_DATE(DHLOG, 'DD') < SANKHYA.SNK_TRUNC_DATE(GETDATE() - 15, 'DD' ) 

   INSERT INTO TEIPCV_MAXIMA
                  (NUFIN 
                  ,CODVEND
                  ,TIPO
                  ,CAIXAMX
                  ,MOVIMENTOMX
                  ,MENSAGEM
                  ,CODERRO
                  ,JSONREQUEST
                  ,DHLOG) 
   VALUES      (
                  @P_NUFIN 
                  ,@P_CODVEND
                  ,@P_TIPO
                  ,@P_CAIXAMX
                  ,@P_MOVIMENTOMX
                  ,@P_MENSAGEM
                  ,@P_CODERRO
                  ,@P_JSONREQUEST
                  ,GETDATE()); 
END;
GO

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

IF NOT EXISTS( SELECT 1 FROM TSISNK WHERE OBJETO = 'STP_MAX_OBTEM_TRIB')
BEGIN
	IF SANKHYA.SNK_OBJETO_EXISTE('STP_MAX_OBTEM_TRIB') > 0 
	  DROP PROCEDURE STP_MAX_OBTEM_TRIB;

	EXECUTE('
	CREATE PROCEDURE STP_MAX_OBTEM_TRIB(
		 @P_CODUFORIG        INT,
		 @P_CODUFDEST        INT,
		 @P_CODPROD          INT,
		 @P_CODGRUPOPROD     INT,
		 @P_GIPROD           INT,
		 @P_GIPROD2          INT,
		 @P_CODEMP           INT,
		 @P_GIGRUPOPROD      INT,
		 @V_ALIQSUBTRIB      FLOAT OUT,
		 @V_ALIQUOTA         FLOAT OUT,
		 @V_CODTRIB          INT OUT,
		 @V_CUSCOMICMSBASEST CHAR OUT,
		 @V_MARGLUCRO        FLOAT OUT,
		 @V_REDBASE          FLOAT OUT,
		 @V_REDBASEST        FLOAT OUT,
		 @V_REPPERCBASEICMS  FLOAT OUT,
		 @V_PRIORIDADE       INT OUT,
		 @P_COUNT			 INT)
AS
BEGIN
    SELECT @V_ALIQSUBTRIB = T.ALIQSUBTRIB,
           @V_ALIQUOTA = T.ALIQUOTA,
           @V_CODTRIB = T.CODTRIB,
           @V_CUSCOMICMSBASEST = T.CUSCOMICMSBASEST,
           @V_MARGLUCRO = T.MARGLUCRO,
           @V_REDBASE = T.REDBASE,
           @V_REDBASEST = T.REDBASEST,
           @V_REPPERCBASEICMS = T.REPPERCBASEICMS,
           @V_PRIORIDADE = T.PRIORIDADE
    FROM   (SELECT 
    			   ROW_NUMBER() OVER(ORDER BY I.ALIQSUBTRIB) AS linhas,
                   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 ) )) T
    WHERE  @P_COUNT = ''1''
END
	')
END
GO

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

CREATE PROCEDURE STP_TRIBUTACAO_MAXIMAUF
AS
  BEGIN TRY
      /* LIMPANDO A TABELA DE TRIBUTACAO MAXIMA */
      EXECUTE ('TRUNCATE TABLE TRIBUTACAO_MAXIMA')

      BEGIN TRAN

      SELECT T2.* INTO #TRIBUTOS_MAXIMA FROM (
            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
                   , T.CODUF                                    AS CODUF
                   , T.CODGRUPOPROD                             AS CODGRUPOPROD
                   , T.GRUPOICMS                                AS GRUPOICMS
                   , T.GRUPOICMS2                               AS GRUPOICMS2
                   , T.GIGRUPOPROD                              AS GIGRUPOPROD
                   , 1                                          AS CODOPER
                   , 0                                          AS CODCLI
                   , ISNULL (ALIQSUBTRIB, 0)                    AS ALIQICMS1
                   , ISNULL (ALIQSUBTRIB, 0)                    AS ALIQICMS1FONTE
                   , ISNULL (ALIQUOTA, 0)                    AS ALIQICMS2
                   , ISNULL (ALIQUOTA, 0)                    AS ALIQICMS2FONTE
                   , ISNULL( PERCSTFCPINT , 0 )                 AS ALIQICMSFECP  --Fundo Combate a Pobreza ST
                   , ISNULL( PERCICMSFCPINT , 0 )               AS PERACRESCIMOFUNCEP  --Fundo Combate a Pobreza ICMS INTERNO
                   , ISNULL (ALIQUOTA, 0)                       AS CODICM
                   , ISNULL (ALIQUOTA, 0)                       AS CODICMPF
                   , ISNULL (ALIQUOTA, 0)                       AS CODICMPRODRURAL
                   , ISNULL (ALIQUOTA, 0)                       AS CODICMTAB
                   , ISNULL (ALIQUOTA, 0)                       AS CODICMTABPF
                   , ISNULL (MARGLUCRO, 0)                      AS IVA
                   , ISNULL (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
                   , ISNULL((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
                   , ISNULL (REPPERCBASEICMS, 0)                AS PERDESCREPASSE
                   , 0                                          AS PERDESCSUFRAMA
                   , 0                                          AS RIOLOGISENTOST
                   , SITTRIBUT                                  AS SITTRIBUT
                   , ISNULL(SITTRIBUTPF, SITTRIBUT)             AS SITTRIBUTPF    
                   , 'P'                                        AS TIPOCALCULOGNRE
                   , 0                                          AS TV9ISENTOST
                   , ISNULL(CUSCOMICMSBASEST, 'N')              AS USAVALORULTENTBASEST
                   , ISNULL(CUSCOMICMSBASEST, 'N')              AS USAVALORULTENTBASEST2
                   , 'N'                                        AS USAVLULTENTMEDIOBASEST
                   , 'N'                                        AS UTILIZAPERCBASEREDPF
                   , 0                                          AS CODFISCALVENDAPRONTAENT
                   , 0                                          AS CODFISCALVENDAPRONTAENTINTER
                   , 0                                          AS CODFISCALBONIFIC
                   , 0                                          AS CODFISCALBONIFICINTER
                   , PRIORIDADE                                 AS PRIORIDADE
                   , 0                                          AS PERCBASEREDCONSUMIDOR
                   , 0                                          AS PERCREDPVENDASIMPLESNAC
                   , T.PERDIFERIMENTOICMS                      AS PERDIFERIMENTOICMS
                   , CODGRUPOTRIBUT                            AS CODGRUPOTRIBUT
            FROM   (SELECT I.ALIQSUBTRIB
                           , I.ALIQUOTA
                           , I.CODTRIB
                           , I.CUSCOMICMSBASEST
                           , I.MARGLUCRO
                           , I.REDBASE
                           , I.REDBASEST
                           , I.REPPERCBASEICMS
                           , I.PERCSTFCPINT
                           , I.OUTORGA          AS PERDIFERIMENTOICMS
                           , ISNULL(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 
                                          ISNULL(( 
                                                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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD')
                                                                                     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) T2;

              


      MERGE INTO TRIBUTACAO_MAXIMA TM
      USING(  
      
                  SELECT T.*
                            FROM #TRIBUTOS_MAXIMA T
                           WHERE T.PRIORIDADE =
                                    (SELECT MIN( PRIORIDADE )
                                       FROM #TRIBUTOS_MAXIMA 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 (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.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 TRAN
  END TRY

  BEGIN CATCH
      IF( @@TRANCOUNT > 0 )
        ROLLBACK TRAN;

      THROW 5100, 'FALHA AO PREPARAR TRIBUTAÇÃO PARA SER ENVIADA À MÁXIMA.', 1;
  END CATCH;

GO 

GO

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

CREATE TRIGGER TRG_DLT_TGFCAB_MAXIMA ON TGFCAB
	FOR DELETE AS

	DECLARE
	  @P_VALIDAR BIT
	, @OLD_NUNOTA VARCHAR(100)
	, @OLD_AD_MAXIMA_NUMCAR VARCHAR(100)
	, @OLD_AD_MAXIMA_IDPEDIDO VARCHAR(100)
	, @OLD_AD_MAXIMA_PEDIDO VARCHAR(100)
	, @OLD_PESOBRUTO VARCHAR(100)

	BEGIN

		SELECT @OLD_NUNOTA = T.NUNOTA 
			, @OLD_AD_MAXIMA_NUMCAR = T.AD_MAXIMA_NUMCAR
			, @OLD_AD_MAXIMA_IDPEDIDO = T.AD_MAXIMA_IDPEDIDO
			, @OLD_AD_MAXIMA_PEDIDO = T.AD_MAXIMA_PEDIDO
			, @OLD_PESOBRUTO 		= T.PESOBRUTO		
		FROM DELETED T 

		IF(@OLD_AD_MAXIMA_IDPEDIDO IS NOT NULL) 
		 BEGIN  
		   IF (SANKHYA.STP_GET_ATUALIZANDO() = 1)
		   BEGIN
			RETURN
		   END
		   EXEC SANKHYA.FPODEVALIDAR 'TGFCAB', @P_VALIDAR OUTPUT
		END
			  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
GO

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

CREATE TRIGGER SANKHYA.TRG_UPD_TGFCAB_MAXIMA ON TGFCAB
FOR UPDATE AS
 DECLARE @VALIDAR      BIT	    
	  , @V_COUNT INT
	  , @P_NUMCAR INT
	  , @TIPOVENDA INT
	  , @NEW_CODVEND INT
	  , @NEW_TIPMOV VARCHAR(100)
	  , @NEW_STATUSNOTA CHAR(1)
	  , @OLD_STATUSNOTA CHAR(1)
	  , @NEW_ORDEMCARGA INT
	  , @OLD_ORDEMCARGA INT
	  , @NEW_AD_MAXIMA_NUMCAR VARCHAR(50)
	  , @NEW_AD_MAXIMA_IDPEDIDO VARCHAR(100)
	  , @NEW_AD_MAXIMA_PEDIDO VARCHAR(100)
	  , @NEW_DH_MAXIMA_NUVEM DATE
	  , @NEW_DH_MAXIMA_LANCAMENTO DATE
	  , @V_BLOQUEIA_DUPLICACAO CHAR(1)
	  , @MENSAGEM VARCHAR(100)
	  , @NEW_CODTIPOPER INT
	  , @NEW_DHTIPOPER DATETIME
BEGIN
	  /* SE ATUALIZANDO */
      IF (SANKHYA.STP_GET_ATUALIZANDO() = 1)
	  BEGIN
        RETURN
      END 
      
      EXEC SANKHYA.FPODEVALIDAR 'TGFCAB', @VALIDAR OUTPUT
	  /* OBTENDO OS DADOS*/
       SELECT @TIPOVENDA = T.AD_MAXIMA_TIPOVENDA 
		, @NEW_CODVEND 				= INS.CODVEND 
		, @NEW_STATUSNOTA 		= INS.STATUSNOTA
		, @OLD_STATUSNOTA 		= DEL.STATUSNOTA
		, @NEW_ORDEMCARGA 		= INS.ORDEMCARGA
		, @OLD_ORDEMCARGA 		= DEL.ORDEMCARGA
		, @NEW_TIPMOV 			= INS.TIPMOV
		, @NEW_AD_MAXIMA_NUMCAR = INS.AD_MAXIMA_NUMCAR
		, @NEW_AD_MAXIMA_IDPEDIDO = INS.AD_MAXIMA_IDPEDIDO   
        , @NEW_AD_MAXIMA_PEDIDO     = INS.AD_MAXIMA_PEDIDO
        , @NEW_DH_MAXIMA_NUVEM      = INS.DH_MAXIMA_NUVEM
        , @NEW_DH_MAXIMA_LANCAMENTO = INS.DH_MAXIMA_LANCAMENTO
		, @NEW_CODTIPOPER			= INS.CODTIPOPER
		, @NEW_DHTIPOPER			= INS.DHTIPOPER
	FROM INSERTED INS LEFT JOIN DELETED DEL ON DEL.NUNOTA = INS.NUNOTA 
	   , TGFTOP T 
	WHERE INS.TIPMOV IN ('P', 'V')
	   AND T.CODTIPOPER = INS.CODTIPOPER
	   AND T.DHALTER = INS.DHTIPOPER
      
      --SE PEDIDO/NOTA VEIO DA MÁXIMA 
      IF @NEW_AD_MAXIMA_IDPEDIDO IS NOT NULL 
		BEGIN
		
            --SE JÁ EXISTE NOTA OU PEDIDO COM O MESMO ID ( ESTÁ DUPLICANDO ), LIMPA OS CAMPOS DE CONTROLE DA MAXIMA 
            --OU BLOQUEIA A DUPLICAÇÃO DE ACORDO COM A CONFIGURAÇÃO DO PARAMETRO            
										 
                  --VERIFICA SE DEVE BLOQUEAR A DUPLICACAO
                  SELECT @V_BLOQUEIA_DUPLICACAO = ISNULL(MAX(LOGICO) , 'N') FROM TSIPAR WHERE CHAVE = 'BLOQDUPLPDMX';
                  
                  --BLOQUEIA A DUPLICACAO 
                  IF @V_BLOQUEIA_DUPLICACAO = 'S' BEGIN
                        RAISERROR('NÃO É PERMITIDO DUPLICAR PEDIDO/NOTA DE ORIGEM MÁXIMA. CAMPO: AD_MAXIMA_IDPEDIDO: ', 16, 1);
                  END 
                  ELSE
					  --SE NÃO BLOQUEOU ENTÃO LIMPA OS CAMPOS DE CONTROLE DA MAXIMA 
					  SET @NEW_AD_MAXIMA_IDPEDIDO   = NULL      
					  SET @NEW_AD_MAXIMA_PEDIDO     = NULL
					  SET @NEW_DH_MAXIMA_NUVEM      = NULL
					  SET @NEW_DH_MAXIMA_LANCAMENTO = NULL
					  SET @NEW_AD_MAXIMA_NUMCAR     = NULL
				END           
		
	--SE EH UPDATE    
    
        /* SE ESTÁ RETIRANDO A ORDEM DE CARGA */
          IF @NEW_TIPMOV = 'P' AND ISNULL( @OLD_ORDEMCARGA, 0 ) <> 0 AND ISNULL( @NEW_ORDEMCARGA, 0 ) = 0  
		  BEGIN
			
			UPDATE TGFCAB SET AD_MAXIMA_NUMCAR = NULL
      
			RETURN         
                    
        END
    
        /* SE ESTÁ CONFIRMANDO A NOTA E AINDA NÃO TEM  NUMERO DE CARREGAMENTO */
       IF @NEW_TIPMOV = 'V' AND @NEW_STATUSNOTA = 'L' AND @NEW_AD_MAXIMA_NUMCAR IS NULL 
	   BEGIN
			
            /* VERIFICANDO SE A TOP É DE ABASTECIMENTO DE ESTOQUE VEÍCULO */ 
            SELECT @V_COUNT = COUNT(1)  
            FROM TGFTOP T
            WHERE T.AD_MAXIMA_TIPOVENDA = 13 /* ABASTECIMENTO ESTOQUE VEÍCULO PRONTA ENTREGA */
            AND @NEW_TIPMOV = 'V' 
            AND T.CODTIPOPER = @NEW_CODTIPOPER
            AND T.DHALTER    = @NEW_DHTIPOPER;
    
            /* SE A TOP NÃO É DE ABASTECIMENTO DE ESTOQUE VEÍCULO */ 
            IF @V_COUNT = 0 
			BEGIN
			
                RETURN;
            END 
    
            /* SE O VENDEDOR NÃO FOI INFORMADO */
            IF ISNULL( @NEW_CODVEND , 0 ) = 0 
			BEGIN
			
                RAISERROR('-20101 OBRIGATÓRIO INFORMAR O VENDEDOR EM NOTA DE REMESSA PARA VENDA FORA DO ESTABELECIMENTO!' , 16, 1);
            END 
    
            /* VERIFICANDO SE JAH TEM CARREGAMENTO ABERTO PARA ESTE VENDEDOR */
            SELECT @P_NUMCAR = ISNULL( MAX(NUMCAR) , 0 ) 
            FROM AD_MAXIMA_CARREGAMENTOS 
            WHERE CODVEND = @NEW_CODVEND
            AND DTFECHAMENTO IS NULL
    
            /* SE NÃO TEM CARREGAMENTO ABERTO */
            IF @P_NUMCAR = 0 
			BEGIN
				
                /* OBTENDO PRÓXIMO NÚMERO DE CARREGAMENTO */
                SELECT @P_NUMCAR = ISNULL( MAX( NUMCAR ) , 0 ) + 1 
                FROM AD_MAXIMA_CARREGAMENTOS
    
                /* INSERINDO NOVO CARREGAMENTO */
                INSERT INTO AD_MAXIMA_CARREGAMENTOS (NUMCAR, CODVEND ) 
                VALUES ( @P_NUMCAR , @NEW_CODVEND )
    
            END 
    
            /* SETANDO NRO DO CARREGAMENTO NA NOTA */
           UPDATE TGFCAB 
		   SET AD_MAXIMA_NUMCAR = 'PE' + CAST( ISNULL(  @P_NUMCAR, ' ' ) AS VARCHAR(48) )  /* PREFIXO 'PE' IDENTIFICA QUE É DE PRONTA ENTREGA */
		   WHERE NUNOTA IN ( SELECT NUNOTA FROM INSERTED ) /* PREFIXO 'PE' IDENTIFICA QUE É DE PRONTA ENTREGA */
           
      END
	END
GO

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

CREATE TRIGGER TRG_MAXIMA_AD_MAXCONF 
ON AD_MAXCONF
FOR INSERT AS
DECLARE @V_COUNT INT
BEGIN
SELECT @V_COUNT = COUNT(1) FROM AD_MAXCONF

  IF @V_COUNT > 1
    EXEC SANKHYA.SNK_ERROR  'SÓ É PERMITIDO UMA LINHA DE CONFIGURAÇÃO!' 
END
GO

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

CREATE VIEW VW_MAXIMA_TRIBUTOS_M
AS 
SELECT   ROW_NUMBER() OVER( ORDER BY CODEMP ,CODFILIALNF ,UFDESTINO ,CODOPER ) 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
GO

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

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

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

CREATE 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
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL( T.CODCONTA , '') AS VARCHAR(100) )
										+ CAST( ISNULL(  T.CODBANCO, '')  AS VARCHAR(100) )
										+ CAST( ISNULL(  T.AG , '') AS VARCHAR(100) )
										+ CAST( ISNULL(  T.NUMCONTA, '')  AS VARCHAR(100) ) 
										+ CAST( ISNULL(  T.CODFILIAL, '')  AS VARCHAR(100) )
										+ CAST( ISNULL(  T.DESCRICAO, '')   AS VARCHAR(100) )
										+ CAST( ISNULL(  T.TIPO, '')  AS VARCHAR(100) ) 
                             ) AS MD5LINHA
                ,T.*
            FROM ( 
					SELECT CAST(CODCTABCOINT AS VARCHAR(100) ) 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;  											
GO

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

CREATE 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
                , SANKHYA.SNK_GET_MD5(      CAST( ISNULL( T.CODFISCAL, '') AS VARCHAR(100) )
								          + CAST( ISNULL(  T.DESCCFO , '') AS VARCHAR(100) )
                             ) AS MD5LINHA
                ,T.*
            FROM ( 
					SELECT CAST(CODCFO AS VARCHAR(100) ) AS CHAVE
						  ,	CODCFO AS CODFISCAL  , DESCRCFO AS DESCCFO 
					FROM TGFCFO
                ) T
   )T2;  					
GO

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

CREATE VIEW VW_MAXIMA_NATUREZAS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 37 ) AS MD5
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(  T.CODCATEGORIADESPESA, '')  AS VARCHAR(100) ) 
										+ CAST( ISNULL(  T.DESCRICAO , '')   AS VARCHAR(100) )
										+ CAST( ISNULL(  T.ATIVO , '')   AS VARCHAR(100) )
                             ) AS MD5LINHA
                ,T.*
            FROM ( 
                    SELECT 
						  CAST(NAT.CODNAT AS VARCHAR(100) ) 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;  						
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODTIPVENDA, '') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.DESCRTIPVENDA , '')   AS VARCHAR(100) )
                 + CAST( ISNULL(  T.EMITEBOLETA , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PRAZOMAX , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VENDAMIN , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PRAZOMEDMAX , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.NROPARCELAS , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODTAB , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TIPOPRAZO  , '') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VLMINPEDIDO , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TIPOENTRADA , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TIPOVENDA , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VENDABK , '')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PERTXFIM, '') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
            SELECT CAST(TPV.CODTIPVENDA AS VARCHAR(100) ) 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 
               , ISNULL(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;                                          
GO

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

CREATE VIEW VW_MAXIMA_PRACA AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 12  ) AS MD5
				, SANKHYA.SNK_GET_MD5(     CAST( ISNULL( T.CODPRACA, '')  AS VARCHAR(100) )
										 + CAST( ISNULL(  T.NUMREGIAO , '')  AS VARCHAR(100) )
										 + CAST( ISNULL(  T.ROTA , '')  AS VARCHAR(100) )
										 + CAST( ISNULL(  T.SITUACAO , '')  AS VARCHAR(100) )
										 + CAST( ISNULL(  T.PRACA , '')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(NTA.CODTAB AS VARCHAR(100) ) 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) )	)
				) T
   )T2;  							   																			 																			 
GO

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

CREATE VIEW VW_MAXIMA_REGIAO AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 2) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMREGIAO, '') AS VARCHAR(100) )
								 + CAST( ISNULL(  T.REGIAO , '')  AS VARCHAR(100) )
								 + CAST( ISNULL(  T.STATUS , '')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(NTA.CODTAB AS VARCHAR(100) ) 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') )))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;
GO

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

CREATE 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
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODFILIAL, '') AS VARCHAR(100) )
								 + CAST( ISNULL(  T.CODPROD , '')  AS VARCHAR(100) )
								 + CAST( ISNULL(  T.PROIBIDAVENDA , '')  AS VARCHAR(100) )
								 + CAST( ISNULL(  T.ENVIARFORCAVENDAS , '')  AS VARCHAR(100) )
								 + CAST( ISNULL(  T.MULTIPLO , '')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  /* PRODUTOS POR EMPRESA - TGFPEM */
					  SELECT DISTINCT RIGHT('00000' + CAST(  PEM.CODEMP AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( PEM.CODPROD AS VARCHAR(10) ) , 10 ) AS CHAVE
					                , PEM.CODEMP AS CODFILIAL
									, PEM.CODPROD 
									, 'N' AS PROIBIDAVENDA
									, 'S' AS ENVIARFORCAVENDAS
									, ISNULL(P.AGRUPMIN,1) 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 EXCEÇÃO POR EMPRESA */
					  SELECT DISTINCT RIGHT('00000' + CAST(  E.CODEMP  AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( P.CODPROD AS VARCHAR(10) ) , 10 ) AS CHAVE
									, E.CODEMP AS CODFILIAL
									, P.CODPROD 
									, 'N' AS PROIBIDAVENDA
									, 'S' AS ENVIARFORCAVENDAS
									, ISNULL(P.AGRUPMIN,1) 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 EXCEÇÃO POR EMPRESA */
					  SELECT DISTINCT RIGHT('00000' + CAST(  E.CODEMP AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( P.CODPROD AS VARCHAR(10) ) , 10 ) AS CHAVE
									, E.CODEMP AS CODFILIAL
									, P.CODPROD 
									, 'N' AS PROIBIDAVENDA
									, 'S' AS ENVIARFORCAVENDAS
									, ISNULL(P.AGRUPMIN,1) 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;
GO

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

CREATE VIEW VW_MAXIMA_VENDEDOR AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 7  ) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.BLOQUEIO, ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODSUPERVISOR , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODUSUR , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.EMAIL , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.NOME , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.TELEFONE1 , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.TIPOVEND , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.USADEBCREDRCA , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODFILIAL , ' ')  AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODCLIRCA , ' ')  AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
            SELECT CAST(VEN.CODVEND AS VARCHAR(100) ) AS CHAVE
               , CASE WHEN VEN.ATIVO = 'S' THEN 'N' ELSE 'S' END AS BLOQUEIO
               , ISNULL( VEN.CODGER, 1 ) AS CODSUPERVISOR
               , VEN.CODVEND AS CODUSUR
               , VEN.EMAIL AS EMAIL
               , VEN.APELIDO AS NOME
               , ISNULL( (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;          
GO

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

CREATE VIEW VW_MAXIMA_SUPERVISOR AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 8  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODSUPERVISOR, ' ') AS VARCHAR(100) )
								 + CAST( ISNULL(  T.NOME , ' ')  AS VARCHAR(100) )
								 + CAST( ISNULL(  T.POSICAO , ' ')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(VEN.CODVEND AS VARCHAR(100) ) 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	  				  
GO

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

CREATE VIEW VW_MAXIMA_MARCA AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 23  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODMARCA, ' ') AS VARCHAR(100) )
								 + CAST( ISNULL(  T.MARCA , ' ')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT 
						 CAST(CODIGO AS VARCHAR(100) ) AS CHAVE
						,CODIGO AS CODMARCA 
						,DESCRICAO AS MARCA
					  FROM TGFMAR MAR
		) T
	)T2;					  					  
GO

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

CREATE 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
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODPARC, ' ') AS VARCHAR(100) )
                                 + CAST( ISNULL(  T.CODTIPVENDA , ' ')  AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                      SELECT   DISTINCT RIGHT('0000000000' + CAST( PAR.CODPARC AS VARCHAR(10) ) , 10 ) + RIGHT('00000' + CAST(  TPV.CODTIPVENDA AS VARCHAR(5) ) , 5 ) 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 )
        ) T
    )T2;                                                    
GO

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

CREATE VIEW VW_MAXIMA_COBRANCAS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 9  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCOB, ' ') AS VARCHAR(100) )
								   + CAST( ISNULL(  T.COBRANCA , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.BOLETO , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.CARTAO , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.CODFILIAL , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.NIVELVENDA , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.PRAZOMAXIMOVENDA , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.COBRANCABROKER , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.TXJUROS , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.PERCMULTA , ' ')   AS VARCHAR(100) )
								   + CAST( ISNULL(  T.TIPOCOBRANCA , ' ')  AS VARCHAR(100) )
								   + CAST( ISNULL(  T.VLMINPEDIDO , ' ')   AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT RIGHT('00000' + CAST(  TIT.CODTIPTIT AS VARCHAR(5) ) , 5 ) 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;				  
GO

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

CREATE VIEW VW_MAXIMA_CLIENTESCREDITOS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 17  ) AS MD5
                , SANKHYA.SNK_GET_MD5(       CAST( ISNULL( T.CODCLI, ' ') AS VARCHAR(100) )
                						   + CAST( ISNULL( T.NOMEPARC, ' ') AS VARCHAR(100) )
                                           + CAST( ISNULL( T.VLLIMITE, ' ') AS VARCHAR(100) )
                                           + CAST( ISNULL( T.VLTITULOS, ' ') AS VARCHAR(100) )                                           
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                      SELECT CAST(CODPARC AS VARCHAR(100) ) AS CHAVE
                           , CODPARC AS CODCLI
                           , NOMEPARC
                           , ISNULL( PAR.LIMCRED, 0 ) AS VLLIMITE
                           , ISNULL( ( SELECT SUM(TB.DEBITO) FROM(
                            	SELECT ISNULL(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
                                UNION
                                SELECT ISNULL(SUM(F.VLRDESDOB),0) AS DEBITO
                                    FROM TGFFIN F
                                    ,(SELECT LOGICO AS LIMCREDMATRIZ FROM TSIPAR WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA > CONVERT(DATETIME, CONVERT(DATE, GETDATE()))
                                    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
                                UNION
                                SELECT ISNULL(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 )
                                UNION 
                                SELECT ISNULL(SUM(F.VLRDESDOB),0) AS DEBITO
                                    FROM TGFFIN F
                                    ,(SELECT LOGICO AS LIMCREDMATRIZ FROM TSIPAR WHERE CHAVE = 'LIMCREDMATRIZ') PARAM
                                    WHERE F.DHBAIXA > CONVERT(DATETIME, CONVERT(DATE, GETDATE()))
                                    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 TB
                             ) , 0 ) AS VLTITULOS
                           , 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;
GO

GO

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

CREATE VIEW VW_MAX_CLIENTESENDERECOS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 14  ) AS MD5
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCLI, ' ') AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.CODENDENTCLI , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.CODBAIRROENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.BAIRROENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.ESTENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.CEPENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.ENDERENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.COMPLEMENTOENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.CODPRACAENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.NUMEROENT , ' ')  AS VARCHAR(100) )
                                   + CAST( ISNULL(  T.MUNICENT , ' ')  AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
             SELECT  /* ENDEREÇO DE ENTREGA DOS CONTATOS */
                        RIGHT('0000000000' + CAST( CTT.CODCONTATO AS VARCHAR(10) ) , 10 ) + RIGHT('0000000000' + CAST( PAR.CODPARC AS VARCHAR(10) ) , 10 ) AS CHAVE
                       ,PAR.CODPARC AS CODCLI
                       ,RIGHT('0000000000' + CAST( CTT.CODCONTATO AS VARCHAR(10) ) , 10 ) + RIGHT('0000000000' + CAST( PAR.CODPARC AS VARCHAR(10) ) , 10 ) 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;                             
GO

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

CREATE VIEW VW_MAXIMA_EMPRESA AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 10  ) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODEMP, ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.RAZAOSOCIAL , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CGC , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.INSCESTAD , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.ENDERECO  , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.BAIRRO , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.UF , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CIDADE , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TELEFONE , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.FAX , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.UTILIZA_VENDA_POR_EMBALAGEM , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TRABCOMIPI , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODPARC , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.UTILIZAWMS , ' ')  AS VARCHAR(100) )
                 + CAST( ISNULL(  T.ATIVO , ' ') AS VARCHAR(100) )   
             ) AS MD5LINHA
        ,T.*
      FROM ( 
            SELECT CAST(EMP.CODEMP AS VARCHAR(100) ) 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
               , ISNULL( (   SELECT TRABCOMIPI
                   FROM   TGFEMP TGF
                   WHERE  TGF.CODEMP = EMP.CODEMP )
                 , 'N') AS TRABCOMIPI
               , EMP.CODPARC
               , ISNULL( (   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;  
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.VALORDESC , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODCLI , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VLRJURO , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODFILIAL , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VALOR , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.ATRASO , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.PREST , ' ') AS VARCHAR(100) )
				  + CAST( ISNULL(  convert(varchar, T.DTVENCORIG ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODUSUR , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMCHEQUE , ' ') AS VARCHAR(100) )
				  + CAST( ISNULL(  convert(varchar, T.DTVENC ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VALORORIG , ' ') AS VARCHAR(100) )
				  + CAST( ISNULL(  convert(varchar, T.DTEMISSAO ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODCOB , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.DUPLIC , ' ') AS VARCHAR(100) )
				  + CAST( ISNULL(  convert(varchar, T.DTPAG ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VLRMULTA  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CARTORIO , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.PROTESTO , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.RECEBIVEL , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.AGENCIA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMBANCO , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMCARTEIRA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODCLIENTENOBANCO , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODBARRA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.LINHADIG , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NOSSONUMBCO , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.ID_ERP , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
      SELECT CAST(FIN.NUFIN AS VARCHAR(100) ) AS CHAVE 
       , FIN.VLRDESC AS VALORDESC
           , FIN.CODPARC AS CODCLI
           , FIN.VLRJURO AS VLRJURO
           , FIN.CODEMP AS CODFILIAL
          , (FIN.VLRDESDOB * ISNULL( FIN.RECDESP, 0 )) AS VALOR
           , ( cast(floor(cast(
                    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
                                 ( cast(floor(cast(getdate() as float)) as datetime)) - FIN.DTVENC
                           END )
                    END as float)) as datetime))
                AS ATRASO
       , CASE WHEN FIN.NUNOTA IS NOT NULL 
          THEN CAST( ISNULL( FIN.DESDOBRAMENTO, 0 )  AS VARCHAR(4) )
          ELSE 'T' + ISNULL( FIN.DESDOBRAMENTO, 0 ) 
          END AS PREST
           , FIN.DTVENCINIC AS DTVENCORIG
           , ISNULL( FIN.CODVEND, 0 ) AS CODUSUR
           , FIN.NUCHQ AS NUMCHEQUE
           , FIN.DTVENC AS DTVENC
           , ( ISNULL( FIN.VLRDESDOB, 0 ) + ( CASE
                WHEN FIN.TIPMULTA = '1' THEN ISNULL( FIN.VLRMULTA, 0 )
                ELSE 0
             END ) + ( CASE
                WHEN FIN.TIPJURO = '1' THEN ISNULL( FIN.VLRJURO, 0 )
                ELSE 0
             END ) + ISNULL( FIN.DESPCART, 0 ) + ISNULL( FIN.VLRVENDOR, 0 ) - ISNULL(
             FIN.VLRDESC
                                                                           ,
             0 ) - ( CASE
                WHEN FIN.IRFRETIDO = 'S' THEN ISNULL( FIN.VLRIRF, 0 )
                ELSE 0
             END ) - ( CASE
                WHEN FIN.ISSRETIDO = 'S' THEN ISNULL( FIN.VLRISS, 0 )
                ELSE 0
             END ) - ( CASE
                WHEN FIN.INSSRETIDO = 'S' THEN ISNULL( FIN.VLRINSS, 0 )
                ELSE 0
             END ) - ISNULL( FIN.CARTAODESC, 0 ) + ISNULL(
             (                                          SELECT SUM( I.VALOR
             * I.TIPIMP )
                                                        FROM   TGFIMF I
                                                        WHERE  I.NUFIN =
                FIN.NUFIN )
                                                   ,0 ) + ISNULL(
             FIN.VLRMULTANEGOC
                                                             ,0 ) + ISNULL(
             FIN.VLRJURONEGOC
                                                                       ,0 )
             - ISNULL( FIN.VLRMULTALIB, 0 ) - ISNULL( FIN.VLRJUROLIB, 0 ) + ISNULL(
             FIN.VLRVARCAMBIAL
                                                                         ,0 )
             ) * ISNULL( FIN.RECDESP, 0 )
                AS VALORORIG
           , FIN.DTNEG AS DTEMISSAO
           , FIN.CODTIPTIT AS CODCOB
           , ISNULL( 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
       , ISNULL( FIN.AD_MAXIMA_RECEBE, 'N') AS RECEBIVEL
        , CTA.CODAGE AS AGENCIA
        , RIGHT('000' + CAST( CTA.CODBCO AS VARCHAR(3) ), 3 ) AS NUMBANCO  
        , CTA.CARTEIRA AS NUMCARTEIRA
    , CTA.CODCTABENEF AS CODCLIENTENOBANCO
    , FIN.CODIGOBARRA AS CODBARRA
        , FIN.LINHADIGITAVEL AS LINHADIG
        , ISNULL( FIN.NOSSONUM , 0 ) AS NOSSONUMBCO
    , ISNULL( 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;         
GO	
GO

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

CREATE 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 charindex(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'+ RIGHT('0000000000' + CAST( CAB.CODEMP AS VARCHAR(5) ),5) + RIGHT('0000000000' + CAST( CAB.ORDEMCARGA AS VARCHAR(10) ) , 10 )
         ELSE NULL END AS NUMCAR
      , CAB.AD_MAXIMA_IDPEDIDO AS ID_PEDIDO
      , CAB.CODTIPOPER
      , CAB.DHTIPOPER
      , SANKHYA.SNK_GET_NOTA_MAXIMA( CAB.NUNOTA ) AS NUNOTA_NOTA
      , CASE WHEN CAB.CODCONTATOENTREGA IS NOT NULL OR CAB.CODCONTATO IS NOT NULL THEN 
            RIGHT( '0000000000' + CAST( ISNULL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ) AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CAB.CODPARC AS VARCHAR(10) ) , 10 )
          ELSE NULL END AS CODENDENTCLI      
       FROM TGFCAB CAB, TGFTOP TPO
        , (SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM AD_MAXCONF) CONF
       WHERE  CAB.TIPMOV = 'P'
       AND    CAB.DTNEG >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') - CONF.QTD_DIAS_HIST_VENDAS
       AND    CAB.CODTIPOPER <> ISNULL(CONF.TOP_ORCAMENTO,0)
       AND    TPO.CODTIPOPER = CAB.CODTIPOPER
            AND     TPO.DHALTER = CAB.DHTIPOPER
       AND     TPO.AD_MAXIMAORIGEMPD IS NOT NULL
   UNION ALL  --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 
            RIGHT( '0000000000' + CAST( ISNULL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ) AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CAB.CODPARC AS VARCHAR(10) ) , 10 )
          ELSE NULL END AS CODENDENTCLI      
     FROM   AD_PEDIDO_MAXIMA PM
      , TGFCAB_EXC CAB, TGFTOP TPO
      , (   SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM   AD_MAXCONF) CONF
     WHERE  CAB.TIPMOV = 'P'
     AND    CAB.DTNEG >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') - CONF.QTD_DIAS_HIST_VENDAS
     AND    CAB.NUNOTA = PM.NUNOTA
     AND    CAB.CODTIPOPER <> ISNULL(CONF.TOP_ORCAMENTO,0)
     AND    TPO.CODTIPOPER = CAB.CODTIPOPER
          AND     TPO.DHALTER = CAB.DHTIPOPER
          AND     TPO.AD_MAXIMAORIGEMPD IS NOT NULL
   UNION ALL  --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 
            RIGHT( '0000000000' + CAST( ISNULL( CAB.CODCONTATOENTREGA, CAB.CODCONTATO ) AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CAB.CODPARC AS VARCHAR(10) ) , 10 )
          ELSE NULL END AS CODENDENTCLI      
     FROM   TGFCAB_EXC CAB, TGFTOP TPO
      , (   SELECT QTD_DIAS_HIST_VENDAS, TOP_ORCAMENTO FROM   AD_MAXCONF) CONF
     WHERE  CAB.TIPMOV = 'P'
     AND    CAB.DTNEG >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') - CONF.QTD_DIAS_HIST_VENDAS
     AND    CAB.CODTIPOPER <> ISNULL(CONF.TOP_ORCAMENTO,0)
     AND    TPO.CODTIPOPER = CAB.CODTIPOPER
          AND     TPO.DHALTER = CAB.DHTIPOPER
          AND     TPO.AD_MAXIMAORIGEMPD IS NOT NULL
          AND NOT EXISTS ( SELECT 1 FROM AD_PEDIDO_MAXIMA PM WHERE PM.NUNOTA = CAB.NUNOTA );          
GO

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

CREATE VIEW VW_MAXIMA_HISTORICO_PD_CAPAS AS 
SELECT T2.*
      FROM   (   SELECT (   SELECT MD5
                            FROM   AD_MAXIMA_INTEGRA
                            WHERE  CHAVE = T.CHAVE AND TIPO = 20 )
                           AS MD5
                      , SANKHYA.SNK_GET_MD5(
                   CAST( ISNULL( T.POSICAO  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMNOTA  , ' ') AS VARCHAR(100) ) 
                  + CAST( ISNULL(  convert(varchar, T.DTFAT ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUNOTA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUNOTA_NOTA   , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.BLOQUEIO , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.ORDEMCARGA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.PENDENTE , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.STATUSNOTA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.MOTIVO  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODCLI  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.TOTPESO  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.ORIGEMPED  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VLTABELA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMPED  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMPEDRCA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CONDVENDA  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODUSUR  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VLATEND  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODCOB  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.VLTOTAL  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  convert(varchar, T.DATA  ,121), ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.OBS1 , ' ') AS VARCHAR(400) )
                  + CAST( ISNULL(  T.CODFORNECFRETE  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.OBS , ' ') AS VARCHAR(400) )
                  + CAST( ISNULL(  T.CODPLPAG  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.TOTVOLUME  , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODPRACA , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODEMITENTE , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.NUMCAR , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.STATUSNFE , ' ') AS VARCHAR(100) )
                  + CAST( ISNULL(  T.CODENDENTCLI , ' ') AS VARCHAR(100) )

            ) AS MD5LINHA
                      , T.*
                 FROM   (   SELECT CAST(PD.NUNOTA AS VARCHAR(100) ) 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 ISNULL( 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
                                 , ISNULL( NOTA.STATUSNFE, ' ') AS STATUSNFE
                                 , PD.*
                                 , ISNULL( 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
                                , ISNULL(TPO.AD_MAXIMAORIGEMPD, 'W')AS ORIGEMPED  
                                , ISNULL(( SELECT SUM(ISNULL(I.VLRCUS * I.QTDNEG, 0))
                                       FROM TGFITE I
                                       WHERE  I.NUNOTA =PD.NUNOTA
                                       AND USOPROD <> 'D'),0) AS VLTABELA
                                , ISNULL( (SELECT SUM( CASE WHEN I.QTDNEG = 0 THEN 0 ELSE ( ( ( I.VLRTOT - I.VLRDESC ) / CASE WHEN I.QTDNEG = 0 THEN 1 ELSE I.QTDNEG END )* I.QTDENTREGUE ) END ) AS VLR_ATENDIDO
                                        FROM   TGFITE I
                                        WHERE  I.NUNOTA = PD.NUNOTA), 0) AS VLATEND
                                , ISNULL(( 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
                                , ISNULL((SELECT SUM(ISNULL(VOA.M3, ISNULL(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
                                , ISNULL((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;
GO

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

CREATE VIEW VW_MAXIMA_ESTOQUE AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 6  ) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODFILIAL , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTBLOQUEADA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VLSTULTENT , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CUSTOREP , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CUSTOREAL , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CUSTOFIN , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTPENDENTE , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTESTGER , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTRESERV , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.DTULTENT , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM (SELECT RIGHT('00000' + CAST( ISNULL(  T.CODEMP, '0')  AS VARCHAR(5) ) , 5 )  + RIGHT('0000000000' + CAST( ISNULL(  T.CODPROD, '0')  AS VARCHAR(10) ) , 10 )  AS CHAVE
               , T.CODEMP AS CODFILIAL
               , T.CODPROD
               , 0 AS QTBLOQUEADA
               , 0.01 AS VLSTULTENT
               , CASE WHEN T.CUSGER = 0 THEN 0.01 ELSE T.CUSGER END AS CUSTOREP
               , CASE WHEN T.CUSGER = 0 THEN 0.01 ELSE T.CUSGER END AS CUSTOREAL
               , CASE WHEN T.CUSGER = 0 THEN 0.01 ELSE T.CUSGER END AS CUSTOFIN
               , 0 AS QTPENDENTE
               , ISNULL( MAX(DTENTRADA), SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') ) AS DTULTENT 
			   , (SUM( T.ESTOQUE ) - SUM(ISNULL(T.WMSBLOQUEADO,0))) AS QTESTGER
               , SUM( ISNULL( T.RESERVADO, 0 ) ) AS QTRESERV
            FROM   (SELECT EST.CODEMP
								, EST.CODPROD
								, EST.RESERVADO AS RESERVADO
								, EST.ESTOQUE AS ESTOQUE
								, EST.DTENTRADA AS DTENTRADA
								, EST.WMSBLOQUEADO AS WMSBLOQUEADO
								, ISNULL(( 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' )
						UNION 
						SELECT EMP.CODEMP
								, PRO.CODPROD
								, 0 AS RESERVADO
								, 0 AS ESTOQUE
								, GETDATE() 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
		   , T.CUSGER
           , ISNULL( DTENTRADA, SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') )) T
  )T2;
GO

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

CREATE VIEW VW_MAXIMA_CLIENTE AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 3) AS MD5
                , SANKHYA.SNK_GET_MD5(       CAST( ISNULL(      T.CODCLI     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODPLPAG     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODCOB     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.FANTASIA     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CLIENTE     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.ATIVO     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.BLOQUEIOSEFAZ     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CAIXAPOSTAL     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CALCULAST     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CEPENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CGCENT     , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  convert(varchar, T.DTULTCOMP ,121), ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODCLIPRINC     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODUSU     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.COMPLEMENTOENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CLASSIFICMS     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.EMAIL     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.EMAILNFE     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.FAXCLI     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.INSCESTADNAUF     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.IMENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.ISENTOIPI     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.NUMEROENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.OBS     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.RG     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.TELENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.TIPOFJ     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.RAZAOSOCIAL     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.BAIRROENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODCIDADE     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.ESTENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.ENDERENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.MUNICENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.LATITUDE     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.LONGITUDE     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.PERCDESC     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.SIMPLESNACIONAL     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODTAB     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODUSUR1     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODUSUR2     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.VALIDARMULTIPLOVENDA     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CONDVENDA5     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CONDVENDA14     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.BLOQUEIODEFINITIVO     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.BLOQUEIO     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CODFILIALNF     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CONSUMIDORFINAL     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.IEENT     , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CLIENTEFONTEST, ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(      T.CONTRIBUINTE     , ' ') AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                    SELECT T.*
                      , CASE WHEN ISNULL(SUGTIPNEGSAID,0) <> 0 THEN SUGTIPNEGSAID ELSE
                        (SELECT MIN(CODTIPVENDA) FROM TGFTPV WHERE SUBTIPOVENDA = 1 AND ATIVO = 'S' AND AD_MAXIMA = 'S' AND CODTIPVENDA <> 0)
                      END AS CODPLPAG
                    FROM ( 
                            SELECT CAST(PAR.CODPARC AS VARCHAR(100) ) 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
                                ,ISNULL( (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
                                ,PAR.RETSTVENDA AS CALCULAST
                                ,ISNULL(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
                                ,SUBSTRING( PAR.OBSERVACOES, 1, 900) AS OBS
                                ,PAR.IDENTINSCESTAD AS RG
                                ,PAR.TIPPESSOA AS TIPOFJ
                                ,PAR.RAZAOSOCIAL
                                ,PAR.CODCID AS CODCIDADE
                                ,PAR.LATITUDE
                                ,PAR.LONGITUDE
                                ,ISNULL(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
                                ,ISNULL(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 ISNULL(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
                                , CASE WHEN PAR.TIPPESSOA = 'F' THEN PAR.NOMEPARC ELSE PAR.RAZAOSOCIAL END 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 ISNULL(ENDE.CODEND, 0) WHEN 0 THEN NULL ELSE ENDE.NOMEEND END AS ENDERENT                               
                                , CASE ISNULL(CID.CODCID, 0)  WHEN 0 THEN NULL ELSE CID.NOMECID  END AS MUNICENT
                                , CASE ISNULL(BAIRRO.CODBAI, 0)  WHEN 0 THEN NULL ELSE BAIRRO.NOMEBAI  END AS BAIRROENT
                                , CASE ISNULL(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
                                , ISNULL( PAR.TELEFONE, 0 ) AS TELENT
                                , CASE ISNULL(CPL_END.CODEND, 0) WHEN 0   THEN NULL ELSE CPL_END.NOMEEND END AS ENDERCOM                               
                                , CASE ISNULL(CPL_CID.CODCID, 0) WHEN 0   THEN NULL ELSE CPL_CID.NOMECID END AS MUNICCOM
                                , CASE ISNULL(CPL_BAI.CODBAI, 0) WHEN 0   THEN NULL ELSE CPL_BAI.NOMEBAI END AS BAIRROCOM
                                , CASE ISNULL(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
                                , ISNULL(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;                                                
GO

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

CREATE VIEW VW_MAXIMA_FORNECEDOR AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 18  ) AS MD5
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CGC_CPF , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.ATIVO , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.NOMECID , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.CODPARC , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.UF , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.NOMEPARC , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.RAZAOSOCIAL , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.ENDER , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.BAIRRO , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.TELFAB , ' ') AS VARCHAR(100) )
                               + CAST( ISNULL(  T.REVENDA  , ' ') AS VARCHAR(100) )
                               
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                       SELECT  CAST(PAR.CODPARC AS VARCHAR(100) ) 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
                                            
GO

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

CREATE VIEW VW_MAXIMA_DEPARTAMENTO AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 5) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODEPTO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.DESCRICAO , ' ') AS VARCHAR(100) )
							   
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(GRU.CODGRUPOPROD AS VARCHAR(100) ) AS CHAVE
					       , GRU.CODGRUPOPROD AS CODEPTO 
						   , GRU.DESCRGRUPOPROD AS DESCRICAO
					  FROM   TGFGRU GRU
					  WHERE  GRU.AD_MAXIMA = 'S'
				   AND       GRU.GRAU = 1
				) T
	)T2;				   		   
GO

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

CREATE VIEW VW_MAXIMA_SECAO
AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 56  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODSEC , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.DESCRICAO , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODEPTO , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(GRU.CODGRUPOPROD AS VARCHAR(100) ) 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;				   				   		   
GO

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

CREATE VIEW VW_MAXIMA_CATEGORIA
AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 57  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCATEGORIA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CATEGORIA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODSEC , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(GRU.CODGRUPOPROD AS VARCHAR(100) ) 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;	   
GO

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

CREATE VIEW VW_MAXIMA_SUBCATEGORIA
AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 58  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODSUBCATEGORIA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.SUBCATEGORIA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODCATEGORIA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODSEC , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT DISTINCT CAST(GRU.CODGRUPOPROD AS VARCHAR(100) ) 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;				   
GO

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

CREATE VIEW VW_MAXIMA_PRODUTOS AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 4) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.SUBCATEGORIA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CATEGORIA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.SECAO     , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.DEPARTAMENTO   , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.DESCRPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODMARCA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.MARCA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.USOPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.REFERENCIA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.ALTURA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODCAT , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODPARCFORN , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODPAT , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.ENDIMAGEM , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.ORIGPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.PERMCOMPPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.PESOBRUTO , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.PESOLIQ , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.QTDEMB , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.USACONTPESOVAR , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.REVENDA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CLASSIFICFISCAL , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.EMBALAGEM , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.EMBALAGEMMASTER , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.UNIDADE , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.UNIDADEMASTER , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.QTUNIT , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.QTUNITCX , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.MULTIPLO , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.VOLUME , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.RESTRICAOTRANSP , ' ') AS VARCHAR(100) )
        + CAST( ISNULL(  convert(varchar, T.DTCADASTRO ,121), ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.DESCRICAO2 , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODPRODPRINC , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.PERCIPIVENDA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODGRUPOTRIBUT , ' ') AS VARCHAR(100) )
             ) 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 CAST(PRO.CODPROD AS VARCHAR(100) ) AS CHAVE
                 , PRO.CODPROD
                 , PRO.DESCRPROD
                 , ISNULL(( 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 ) ) ) , MASCARA_GRUPO ) AS NIVEL01
                 , ISNULL(( SELECT GRU.CODGRUPAI FROM TGFGRU GRU WHERE GRU.CODGRUPOPROD = 
                 ( SELECT GRU.CODGRUPAI FROM TGFGRU GRU WHERE GRU.CODGRUPOPROD = PRO.CODGRUPOPROD ) ) , MASCARA_GRUPO ) AS NIVEL02
                 , ISNULL( ( SELECT GRU.CODGRUPAI FROM TGFGRU GRU WHERE GRU.CODGRUPOPROD = PRO.CODGRUPOPROD ) , MASCARA_GRUPO ) AS NIVEL03
                 , ISNULL( PRO.CODGRUPOPROD , MASCARA_GRUPO ) AS NIVEL04                       
                       , ISNULL( PRO.CODMARCA, 0 ) AS CODMARCA
                       , PRO.MARCA
                       , PRO.USOPROD
                       , ISNULL( PRO.REFERENCIA, PRO.CODPROD ) AS REFERENCIA
                       , PRO.ALTURA
                       , PRO.CODCAT
                       , ISNULL( PRO.CODPARCFORN, 0 ) AS CODPARCFORN
                       , PRO.CODPAT
                       , PRO.ENDIMAGEM
                       , PRO.ORIGPROD
                       , PRO.PERMCOMPPROD
                       , ISNULL( PRO.PESOBRUTO, 0 ) AS PESOBRUTO
                       , ISNULL( PRO.PESOLIQ, 0 ) AS PESOLIQ
                       , ISNULL( 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
                      ,ISNULL( ( SELECT VOA.QUANTIDADE FROM TGFVOA VOA WHERE VOA.CODPROD = PRO.CODPROD AND VOA.CODVOL = PRO.CODVOL ) , 1 ) AS QTUNIT
                      ,ISNULL( ( SELECT VOA.QUANTIDADE FROM TGFVOA VOA WHERE VOA.CODPROD = PRO.CODPROD AND VOA.CODVOL = PRO.CODVOLCOMPRA ) , 1 ) AS QTUNITCX
                      , ISNULL(PRO.AGRUPMIN,1) AS MULTIPLO
                      , PRO.M3 AS VOLUME
                      , PRO.AD_MAXIMA_TIPO AS RESTRICAOTRANSP
                      , SANKHYA.SNK_TRUNC_DATE( PRO.DTALTER , 'DD') AS DTCADASTRO 
                      , PRO.COMPLDESC AS DESCRICAO2
                      , PRO.CODPROD AS CODPRODPRINC
                      ,  (SELECT ISNULL(IPI.PERCENTUAL,0) FROM TGFIPI IPI WHERE IPI.CODIPI = PRO.CODIPI) AS PERCIPIVENDA
                      , MASCARA_GRUPO
                      , ISNULL( PRO.GRUPOICMS, 0 ) AS CODGRUPOTRIBUT
                    FROM TGFPRO PRO 
                    ,( SELECT -999999999 AS MASCARA_GRUPO  FROM TSIPAR  WHERE CHAVE = 'MASCGRUPOPROD') MASK
                    WHERE PRO.AD_MAXIMA = 'S'                      
          ) T
         ) T
      ) T
    ) T
    ) T
  )T2;             
GO

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

CREATE VIEW VW_MAXIMA_TSICID
AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 1  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCID  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODMUNFIS  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.NOMECID  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.UF  , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(CID.CODCID AS VARCHAR(100) ) 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;	
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODTAB , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.NUTAB , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
				 + CAST( ISNULL(  convert(varchar, T.DTVIGOR ,121), ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODREG , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VLRVENDA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CUSTO , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TEMIPIVENDA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PERDESCMAX , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PERACRESCMAX , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
            SELECT RIGHT('00000' + CAST(  TAB.CODTAB AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ) , 10 ) AS CHAVE
                 , TAB.CODTAB
               , TAB.NUTAB
               , PRO.CODPROD
               , TAB.DTVIGOR
               , TAB.CODTAB AS CODREG
               , SANKHYA.SNK_GET_PRECO( TAB.NUTAB, PRO.CODPROD, SANKHYA.SYSDATE() ) AS VLRVENDA
               , ISNULL( ( 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') )
                                  ) , 0.01 ) AS CUSTO
               , PRO.TEMIPIVENDA
               , CASE WHEN CONF.USALIMITEFLEX = 'N' 
                           THEN ISNULL( PRO.DESCMAX, 0 ) 
                           ELSE ISNULL(PRO.DESCMAXFLEX, 0) END AS PERDESCMAX
               , CASE WHEN CONF.USALIMITEFLEX = 'N' 
                           THEN 0
                           ELSE ISNULL(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 ISNULL(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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) )
    ) T
  )T2;                              
GO

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

CREATE VIEW VW_MAXIMA_EMBALAGENS AS 
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 33  ) AS MD5
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODAUXILIAR  , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.UNIDADE , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.CODPROD  , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.EMBALAGEM   , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.QTUNIT , ' ') AS VARCHAR(100) )
                              + CAST( ISNULL(  T.FATORPRECO , ' ') AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                    SELECT 
                       RIGHT('00000' + CAST(  EMP.CODEMP AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( VOA.CODPROD AS VARCHAR(5) ) , 10 ) + VOA.CODVOL AS CHAVE
                      ,VOA.CODBARRA AS CODAUXILIAR 
      ,VOA.CODVOL AS UNIDADE
      ,VOA.CODPROD AS CODPROD 
      ,EMP.CODEMP AS CODFILIAL 
      ,VOL.DESCRVOL AS EMBALAGEM  
      ,1 AS QTUNIT
	  ,CASE WHEN VOA.DIVIDEMULTIPLICA = 'D' THEN ROUND(1 / VOA.QUANTIDADE, 6) ELSE (VOA.MULTIPVLR * VOA.QUANTIDADE) END 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 RIGHT('00000' + CAST(  EMP.CODEMP AS VARCHAR(5) ), 5 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ), 10 ) + 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;    
GO

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

CREATE  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
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCLI , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODUSUR    , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT 
					   RIGHT('00000' + CAST(  CODVEND AS VARCHAR(5) ), 5 ) + RIGHT('0000000000' + CAST( CODPARC AS VARCHAR(10) ), 10 ) AS CHAVE
					  ,RPV.CODPARC AS CODCLI
					  ,RPV.CODVEND AS CODUSUR   
					FROM TGFRPV RPV
			) T
	)T2;
GO

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

CREATE  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
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODPLPAG , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODCOB   , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT RIGHT('00000' + CAST(  PPG.CODTIPVENDA AS VARCHAR(5) ), 5 ) + RIGHT('00000' + CAST(  PPG.CODTIPTITPAD AS VARCHAR(5) ), 5 ) 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;
GO

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

CREATE  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
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODUSUR , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.SALDOCC , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.LIMCREDCC , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
						SELECT CAST(CODVEND AS VARCHAR(100) ) AS CHAVE
							 , CODVEND AS CODUSUR
							 , SALDODISP  AS SALDOCC
							 , 0 AS LIMCREDCC
							FROM TGFVEN 
							WHERE AD_MAXIMA = 'S'
		) T
	)T2;
GO

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

CREATE VIEW VW_MAXIMA_BANCOS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 53  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODBANCO , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.NOME , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT 
					      CAST(CODBCO AS VARCHAR(100) ) AS CHAVE
						, CODBCO AS CODBANCO
						, NOMEBCO AS NOME
					FROM TSIBCO
					WHERE AD_MAXIMA = 'S'
		) T
	)T2;
GO

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

CREATE VIEW VW_MAXIMA_DOCELETRONICO AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 40  ) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMTRANSACAO , ' ') AS VARCHAR(100) )
                + SUBSTRING( T.XMLNFE , 1 , 400 ) 
                + CAST( ISNULL(  T.NUMPEDRCA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMPED , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
          SELECT CAST(CAB.NUNOTA AS VARCHAR(100) ) AS CHAVE
            , CAB.NUNOTA AS NUMTRANSACAO
            , NFE.XML AS XMLNFE
            , CAB.AD_MAXIMA_PEDIDO AS NUMPEDRCA
            , SANKHYA.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 >=  SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DD') - CONF.QTD_DIAS_NOTAS
      ) T
  )T2;        
GO

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

CREATE VIEW VW_MAXIMA_ULTIMACOMPRA AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 42  ) AS MD5
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODCLI , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  convert(varchar, T.DTULTCOMP ,121), ' ') AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                    SELECT CAST(CAB.CODPARC AS VARCHAR(100) ) 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 >=  SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DD') - CONF.QTD_DIAS_NOTAS
                    GROUP BY CAB.CODPARC
        ) T
    )T2;
GO

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

CREATE 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 VEÍCULO PRONTA ENTREGA */
        AND CAB.DTNEG >=  SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') - 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 VEÍCULO ( PRONTA ENTREGA ) */
						 AND CR.TIPMOV = 'V'
						 AND CR.DTNEG >= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') - CONF.QTD_DIAS_NOTAS );		
GO

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

CREATE VIEW VW_MAXIMA_RETORNO_VEICULO AS 
SELECT T.*
, ROUND( T.QTDNEG * T.VLRUNIT, 2 ) AS VLRTOT
FROM (
    SELECT
             EST.CODEMP 
           , EST.CODPROD
           , ISNULL( EST.CODLOCAL , 0 ) AS CODLOCALORIG
           , EST.CONTROLE
           , PRO.USOPROD
           , EST.ESTOQUE AS QTDNEG
           , PRO.CODVOL
           , ISNULL( SANKHYA.SNK_GET_PRECO( TAB.NUTAB  ,PRO.CODPROD , SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) , 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 <= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') ) ) 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;
GO

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

CREATE VIEW VW_MAXIMA_VEICULOS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 22  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODVEICULO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.DESCRICAO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.PLACA  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.MARCA  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.VOLUME  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.PESOCARGAKG   , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.SITUACAO   , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.TIPOVEICULO   , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.PROPRIO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODFILIAL , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.TIPO , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
						SELECT CAST(V.CODVEICULO AS VARCHAR(100) ) 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' -- Médio
										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;						
GO

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

CREATE VIEW VW_MAXIMA_MOTORISTAS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 46  ) AS MD5
                , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.MATRICULA  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.TIPO  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.NOME  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.EMAIL  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.ENVIAFV , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.FONE  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.CELULAR  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  convert(varchar, T.DATA_VALIDADE_CNH ,121), ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.CPF , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.SITUACAO  , ' ') AS VARCHAR(100) )
                                + CAST( ISNULL(  T.CODMOTORISTA  , ' ') AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                    SELECT CAST(PAR.CODPARC AS VARCHAR(100) ) 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;                    
GO

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

CREATE VIEW VW_MAXIMA_FUNCIONARIOS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 26  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.MATRICULA  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.TIPO , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.NOME  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.EMAIL  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.ENVIAFV , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.FONE  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CELULAR  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  convert(varchar, T.DATA_VALIDADE_CNH ,121), ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CPF , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.SITUACAO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODMOTORISTA  , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT CAST(USU.CODUSU AS VARCHAR(100) ) 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;
GO

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

CREATE VIEW VW_MAXIMA_ROTAS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 47  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODROTA  , ' ') AS VARCHAR(100) )
							  + CAST( ISNULL(  T.DESCRICAO  , ' ') AS VARCHAR(100) )
							  + CAST( ISNULL(  T.SITUACAO 		 , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT CAST(CODREG AS VARCHAR(100) ) AS CHAVE
					  , CODREG AS CODROTA 
					  , NOMEREG AS DESCRICAO 
					  , CASE WHEN ATIVA = 'S' THEN 'A' ELSE 'I' END AS SITUACAO 
					FROM TSIREG
		) T
	)T2;
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODPROD , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMPED  , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.QTCORTADA  , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
          SELECT CAST(ITE.NUNOTA AS VARCHAR(100) ) 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 = SANKHYA.SNK_GET_NOTA_MAXIMA( ITE.NUNOTA ) )
          AND ITE.QTDNEG - ITE.QTDENTREGUE > 0
    ) T
  )T2;
GO

GO

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

CREATE 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
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODDESCONTO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  convert(varchar, T.DTINICIO ,121), ' ') AS VARCHAR(100) )								
								+ CAST( ISNULL(  convert(varchar, T.DTFIM ,121), ' ') AS VARCHAR(100) )								
								+ CAST( ISNULL(  T.BASECREDDEBRCA   , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CREDITASOBREPOLITICA , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.TIPO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.PERCDESC   , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.NUMREGIAO  , ' ') AS VARCHAR(100) )
								+ CAST( ISNULL(  T.CODLINHAPROD , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
						SELECT 
						  CAST(N.CODTAB AS VARCHAR(100) ) AS CHAVE
						, ROW_NUMBER() OVER( ORDER BY CODTAB ) 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 <= SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DDMMAAAA')  ) ) 
							
							) AS PERCDESC 
						, CODTAB AS NUMREGIAO 
						, NULL AS CODLINHAPROD
						FROM TGFNTA N
						WHERE N.CODTABFLEX IS NOT NULL
						AND N.AD_MAXIMA = 'S'
		) T
	)T2;						
GO

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

CREATE VIEW VW_MAXIMA_PROMOCOES AS 
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 49  ) AS MD5
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODDESCONTO  , ' ') AS VARCHAR(100) )
				 + CAST( ISNULL(  convert(varchar, T.DTINICIO ,121), ' ') AS VARCHAR(100) )								
				 + CAST( ISNULL(  convert(varchar, T.DTFIM ,121), ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODFILIAL , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODPROD  , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.BASECREDDEBRCA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CREDITASOBREPOLITICA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.PERCDESC  , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TIPO  , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.NUMREGIAO  , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODLINHAPROD , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODCLI , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTINI , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.QTFIM , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
          /* PROMOÇÕES QUE NÃO SÃO POR QUANTIDADE */
          SELECT 
                       RIGHT('0000000000' + CAST( DES.NUPROMOCAO AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ), 10 ) AS CHAVE
                     , RIGHT('0000000000' + CAST( DES.NUPROMOCAO AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ), 10 ) 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   ISNULL(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 SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DD') BETWEEN DES.DTINICIAL AND DES.DTFINAL 
        
		UNION                          
                /* PROMOÇÕES POR QUANTIDADE */
        SELECT 
                       RIGHT('0000000000' + CAST( DES.NUPROMOCAO AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ), 10 ) AS CHAVE
                     , RIGHT('0000000000' + CAST( DES.NUPROMOCAO AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( PRO.CODPROD AS VARCHAR(10) ), 10 ) AS CODDESCONTO 
                     , DES.DTINICIAL AS DTINICIO
                     , DES.DTFINAL AS DTFIM
                     , DES.CODEMP AS CODFILIAL
                     , CASE WHEN PRO.CODPROD = 0 THEN NULL ELSE PRO.CODPROD END 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                     
                     , ISNULL(( SELECT MAX(QTDE) FROM TGFDPQ D WHERE D.NUPROMOCAO = DPQ.NUPROMOCAO AND D.QTDE < DPQ.QTDE ) + 0.01,0)  AS QTINI
                     , DPQ.QTDE AS QTFIM
                      ,'S' AS APLICADESCONTO
                      ,'S' AS ALTERAPTABELA
                      ,'S' AS PRIORITARIA
                    FROM TGFDES DES, TGFPRO PRO, TGFDPQ DPQ
                    WHERE DES.GRUPODESCPARC = '***************'
                    AND   DES.GRUPODESCVEND = '***************'
                    AND   DES.CODLOCAL = 0
                    AND   DES.VLRVENDA = 0
                    AND   ISNULL(DES.USADESCQTD,'N') = 'S'
          AND ISNULL(DES.VLRVENDA, 0 ) = 0
                    AND DPQ.NUPROMOCAO = DES.NUPROMOCAO
                    AND   ( ( DES.CODPROD <> 0 AND DES.CODPROD = PRO.CODPROD ) OR 
                            ( DES.GRUPODESCPROD <> '***************' AND DES.GRUPODESCPROD = PRO.GRUPODESCPROD ) )
                    AND SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DD') BETWEEN DES.DTINICIAL AND DES.DTFINAL 
    ) T
  )T2;
GO

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

CREATE VIEW VW_MAXIMA_VISITAS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 51  ) AS MD5
				, SANKHYA.SNK_GET_MD5( 	      CAST( ISNULL( T.CODCOMPROMISSO , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.CODCLI , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.CODUSUR , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.SEQUENCIA , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.NUMSEMANA , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.PERIODICIDADE , ' ')  AS VARCHAR(100) )
											+ CAST( ISNULL(  T.DIASEMANA , ' ')  AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					SELECT 
					  RIGHT('00000' + CAST(  CODVEND AS VARCHAR(5) ) , 5 ) + RIGHT('0000000000' + CAST( CODPARC AS VARCHAR(5) ), 10 ) AS CHAVE
					, ROW_NUMBER() OVER( ORDER BY CODVEND, CODPARC, SEQVISITA ) 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;						  				
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMCAR , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMNOTA , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMPED , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.SERIE , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODUSUR , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CONDVENDA  , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )                
                + CAST( ISNULL(  convert(varchar, T.DTFAT ,121), ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  convert(varchar, T.DTSAIDA ,121), ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  convert(varchar, T.DTENTREGA ,121), ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  convert(varchar, T.DTCANCEL ,121), ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.VLRTOTAL , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.STATUSNFE , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.MOTIVONFE , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.ESPECIE , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODCLI  , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODPLPAG , ' ') AS VARCHAR(100) )
                + CAST( ISNULL(  T.CODCOB , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
          SELECT CAST(CAB.NUNOTA AS VARCHAR(100) ) AS CHAVE
              , CAB.AD_MAXIMA_NUMCAR AS NUMCAR
              , CAB.NUMNOTA AS NUMNOTA
              , SANKHYA.SNK_GET_PD_MAXIMA( CAB.NUNOTA ) AS NUMPED
              , CAB.SERIENOTA AS SERIE
              , CAB.CODVEND AS CODUSUR
              , ISNULL( 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 >=  (SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DDMMAAAA') - CONF.QTD_DIAS_NOTAS )
            UNION
            SELECT CAST(EXC.NUNOTA AS VARCHAR(100) ) AS CHAVE 
              , '0' AS NUMCAR
              , EXC.NUMNOTA AS NUMNOTA
              , 0 AS NUMPED
              , EXC.SERIENOTA AS SERIE
              , EXC.CODVEND AS CODUSUR
              , ISNULL( 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 >=  (SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DDMMAAAA') - CONF.QTD_DIAS_NOTAS )
    ) T
  )T2;                                       
GO

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

CREATE 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
        , SANKHYA.SNK_GET_MD5(    CAST( ISNULL( T.NUMCAR , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.NUMNOTA , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.NUMPED , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.QT , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.NUMTRANSITEM , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.CODAUXILIAR , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.CODOPER , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.QTCONT , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.PTABELA , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.PUNITCONT , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.PUNIT , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.CUSTOFIN , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.VLIPI , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.ST , ' ') AS VARCHAR(100) )
                    + CAST( ISNULL(  T.QTDEVOL , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
          SELECT RIGHT('0000000000' + CAST( ITE.NUNOTA AS VARCHAR(10) ), 10 ) + RIGHT('00000' + CAST(  ITE.SEQUENCIA AS VARCHAR(5) ), 5 ) AS CHAVE
            , CAB.AD_MAXIMA_NUMCAR AS NUMCAR
            , CAB.NUMNOTA AS NUMNOTA
            , SANKHYA.SNK_GET_PD_MAXIMA( CAB.NUNOTA ) AS NUMPED
            , ITE.CODPROD
            , ITE.QTDNEG AS QT
            , ITE.NUNOTA AS NUMTRANSVENDA
            , ITE.NUNOTA + RIGHT('00000'+ITE.SEQUENCIA, 5) AS NUMTRANSITEM
            , (SELECT ISNULL( 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 ISNULL( ITE.QTDNEG , 1 ) = 0 THEN 1 ELSE ISNULL( 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;        
GO

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

CREATE VIEW VW_MAXIMA_CARREGAMENTOS AS
SELECT T2.* 
FROM (
      SELECT 
          (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 38  ) AS MD5
            , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMCAR , ' ') AS VARCHAR(100) )                 
                 + CAST( ISNULL(  convert(varchar, T.DATAMON ,121), ' ') AS VARCHAR(100) )         
                 + CAST( ISNULL(  convert(varchar, T.DTFECHA ,121), ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  convert(varchar, T.DTSAIDA ,121), ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  convert(varchar, T.DTFAT ,121), ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.ORIGEM_CAR , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODMOTORISTA , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.CODVEICULO , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TOTPESO , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.TOTVOLUME , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.VLTOTAL , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.NUMNOTAS , ' ') AS VARCHAR(100) )
                 + CAST( ISNULL(  T.DESTINO , ' ') AS VARCHAR(100) )
             ) AS MD5LINHA
        ,T.*
      FROM ( 
         SELECT
           RIGHT('00000' + CAST( ORD.CODEMP AS VARCHAR(5) ), 5 ) + RIGHT('0000000000' + CAST( ORD.ORDEMCARGA AS VARCHAR(10) ), 10 ) AS CHAVE 
         , ISNULL(AD_MAXIMA_NUMCAR, 'OC'+ RIGHT('00000' + CAST( ORD.CODEMP AS VARCHAR(5) ), 5 ) + RIGHT('0000000000' + CAST( ORD.ORDEMCARGA AS VARCHAR(10) ), 10 )) 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 <> ISNULL( 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 <> ISNULL( 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 <> ISNULL( 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 <> ISNULL( 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 <> ISNULL( 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 ISNULL( DTRETORNO , SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') ) >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') - CONF.QTD_DIAS_CARREGAMENTO
      AND AD_MAXIMA_NUMCAR IS NOT NULL
      UNION
      SELECT 
           'PE' + CAST( NUMCAR AS VARCHAR(50) ) AS CHAVE
         , 'PE' + CAST( NUMCAR AS VARCHAR(48) ) AS NUMCAR
         , NULL AS DATAMON
         , DTFECHAMENTO AS DTFECHA
         , SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') AS DTSAIDA
         , SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') 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 <> ISNULL( CONF.TOP_ORCAMENTO, 0 )
             AND C.AD_MAXIMA_NUMCAR = 'PE' + CAST( CAR.NUMCAR AS VARCHAR(48) ) ) AS NUMNOTAS
         , NULL AS DESTINO
      FROM AD_MAXIMA_CARREGAMENTOS CAR
        , ( SELECT QTD_DIAS_CARREGAMENTO, TOP_ORCAMENTO FROM AD_MAXCONF ) CONF
      WHERE ISNULL( DTFECHAMENTO , SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') ) >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') - CONF.QTD_DIAS_CARREGAMENTO
       ) T
  )T2;                      
GO

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

CREATE 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';
GO

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

CREATE 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'
		) 
GO

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

CREATE VIEW VW_MAXIMA_REMESSA_SIMBOLICA_D AS 
SELECT ITE.*
    FROM TGFITE ITE
    WHERE ITE.NUNOTA = ( SELECT NUNOTA FROM VW_MAXIMA_REMESSA_SIMBOLICA );
GO

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

CREATE VIEW VW_MAXIMA_ENTRADAS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 65  ) AS MD5
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(   T.NUMTRANSENT , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODCONT , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODDEVOL , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODFILIAL , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODFISCAL , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODOPERACAO , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(  convert(varchar, T.DTENT ,121), ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.ESPECIE , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.SERIE , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.NUMNOTA , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.OBS , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.UF , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.TOTPESO , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.VLFRETE , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.VLST , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODMOTORISTADEVOL , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODUSURDEVOL , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.SITUACAONFE , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.GERANFDEVCLI , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(   T.CODPARC , ' ') AS VARCHAR(100) )
                         ) AS MD5LINHA
                ,T.*
            FROM ( 
                SELECT CAST(CAB.NUNOTA AS VARCHAR(100) ) 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( CAB.OBSERVACAO AS VARCHAR(255) ) AS OBS 
                        , UF_PAR.UF AS UF
                        , ISNULL( CAB.PESO , 0 ) AS TOTPESO
                        , ISNULL( 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 DEVOLUÇÃO DE VENDA */
                    AND CAB.DTNEG >= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') - 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;
GO

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

CREATE VIEW VW_MAXIMA_ENTRADAS_ITENS AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 64  ) AS MD5
				, SANKHYA.SNK_GET_MD5(    CAST( ISNULL(    T.NUMTRANSITEM , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMCAR , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMNOTA , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMPED , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.CODPROD , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.QT , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.QTCONT , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMSEQ , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.CODOPER , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.PTABELA , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.PUNITCONT , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.PUNIT , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.CUSTOFIN , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.VLIPI , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.ST , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.CODDEVOL , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.NUMTRANSENT , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.QTDEVOL , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(    T.CODAUXILIAR , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
				SELECT    RIGHT('0000000000' + CAST( ITE.NUNOTA AS VARCHAR(10) ), 10 ) + RIGHT('00000' + CAST(  ITE.SEQUENCIA AS VARCHAR(5) ), 5 ) AS CHAVE
						, RIGHT('0000000000' + CAST( ITE.NUNOTA AS VARCHAR(10) ), 10 ) + RIGHT('00000' + CAST(  ITE.SEQUENCIA AS VARCHAR(5) ), 5 ) 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 / CASE WHEN ITE.QTDNEG = 0 THEN 1 ELSE ITE.QTDNEG END )	 AS PUNIT
						, 0 AS CUSTOFIN
						, ITE.VLRIPI AS VLIPI
						, ITE.BASESUBSTIT AS ST
						, 1 AS CODDEVOL
						, ITE.NUNOTA AS NUMTRANSENT
						, 0 AS QTDEVOL
						, (SELECT ISNULL( 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;
GO

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

CREATE VIEW VW_MAXIMA_ENTRADAS_LIGACOES AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 65  ) AS MD5
                , SANKHYA.SNK_GET_MD5(     CAST( ISNULL(     T.NUMTRANSENT , ' ') AS VARCHAR(100) )
										 + CAST( ISNULL(     T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
										 + CAST( ISNULL(  convert(varchar, T.DTESTORNO ,121), ' ') AS VARCHAR(100) )
										 + CAST( ISNULL(     T.CODUSUR , ' ') AS VARCHAR(100) )
										 + CAST( ISNULL(     T.VLESTORNO , ' ') AS VARCHAR(100) )
										 + CAST( ISNULL(     T.VLDEVOLUCAO , ' ') AS VARCHAR(100) )
                 ) AS MD5LINHA
                ,T.*
            FROM ( 
                SELECT 
                  RIGHT('0000000000' + CAST( NUMTRANSENT AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( NUMTRANSVENDA AS VARCHAR(10) ), 10 ) AS CHAVE
                  , T.*
                  FROM (
                            SELECT    CAB.NUNOTA AS NUMTRANSENT
                                    , ISNULL(( SELECT MAX(V.NUNOTAORIG) FROM TGFVAR V WHERE V.NUNOTA = CAB.NUNOTA ),0) 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;
GO

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

CREATE 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
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(  T.CODFILIAL  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  T.CODPROD  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  convert(varchar, T.DTPREVENT ,121), ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  T.QTPENDENTE , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  T.SITUACAO  , ' ') AS VARCHAR(100) )
                 ) AS MD5LINHA
                ,T.*
            FROM ( 
				SELECT  
					RIGHT('0000000000' + CAST( CODFILIAL AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CODPROD AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( DTPREVENT AS VARCHAR(10) ), 8 ) 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 >= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') - CONF.QTD_DIAS_COMPRAS_PENDENTE
						AND C.DTPREVENT IS NOT NULL
						GROUP BY 
							  C.CODEMP 
							, I.CODPROD 
							, C.DTPREVENT
				  ) T
            ) T
    )T2;
GO

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

CREATE VIEW VW_MAXIMA_CONTATOS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 70  ) AS MD5
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(     T.CODCLI  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.CODCONTATO   , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.NOMECONTATO  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.CARGO  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  convert(varchar, T.DTNASCIMENTO ,121), ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.EMAIL  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.TELEFONE  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.CELULAR  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.TIPOCONTATO  , ' ') AS VARCHAR(100) )
                 ) AS MD5LINHA
                ,T.*
            FROM ( 
                SELECT 
                      RIGHT('0000000000' + CAST( CTT.CODPARC AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CTT.CODCONTATO AS VARCHAR(10) ), 10 ) AS CHAVE
                    , CTT.CODPARC AS CODCLI
                    , RIGHT('0000000000' + CAST( CTT.CODPARC AS VARCHAR(10) ), 10 ) + RIGHT('0000000000' + CAST( CTT.CODCONTATO AS VARCHAR(10) ), 10 ) 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 AS TIPOCONTATO
                FROM TGFCTT CTT
                , TGFPAR PAR
                WHERE PAR.CODPARC = CTT.CODPARC
                AND PAR.AD_MAXIMA_CLIENTE = 'S'
                AND PAR.CLIENTE = 'S'
            ) T
    )T2;
GO

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

CREATE VIEW VW_MAXIMA_TRANSPORTADORAS AS
SELECT T2.* 
FROM (
            SELECT 
                  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 71  ) AS MD5
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(     T.CODTRANSP  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.TRANSPORTADORA   , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.FANTASIA  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.CGC  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.ENDERECO  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.BAIRRO  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.CIDADE  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.UF  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.TELEFONE  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.REVENDA  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.BLOQUEIO  , ' ') AS VARCHAR(100) )
                                        + CAST( ISNULL(     T.EREDESPACHO  , ' ') AS VARCHAR(100) )
                 ) AS MD5LINHA
                ,T.*
            FROM ( 
                SELECT 
                      RIGHT('0000000000' + CAST( PAR.CODPARC AS VARCHAR(10) ), 10 ) 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;
GO

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

CREATE 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
                , SANKHYA.SNK_GET_MD5(    CAST( ISNULL(     T.CODFILIAL  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(     T.CODPROD   , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(     T.NUMLOTE  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(  convert(varchar, T.DATAFABRICACAO ,121), ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(     T.DTVALIDADE  , ' ') AS VARCHAR(100) )
										+ CAST( ISNULL(     T.QT  , ' ') AS VARCHAR(100) )
                 ) AS MD5LINHA
                ,T.*
            FROM ( 
                      SELECT 
						     RIGHT('0000000000' + CAST( EST.CODEMP AS VARCHAR(5) ), 5 ) + RIGHT('0000000000' + CAST( EST.CODPROD AS VARCHAR(10) ), 10 ) + CAST(EST.CONTROLE AS VARCHAR(100) ) 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;
GO

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

CREATE 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
               , SANKHYA.SNK_GET_MD5(  CAST( ISNULL(     T.CODMETA  , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.CODUSUR   , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.TIPOMETA  , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.CODIGO  , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.CODFILIAL  , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(  convert(varchar, T.DATAINICIAL ,121), ' ') AS VARCHAR(100) )
               + CAST( ISNULL(  convert(varchar, T.DATAFINAL ,121), ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.VLVENDAPREV  , ' ') AS VARCHAR(100) )
                           + CAST( ISNULL(     T.QTVENDAPREV  , ' ') AS VARCHAR(100) )
                     ) AS MD5LINHA
               ,T.*
           FROM (
             SELECT
                   RIGHT('00000' + CAST( CFG.CODMETA AS VARCHAR(5) ), 5 ) + RIGHT('00000' + CAST( MET.CODVEND AS VARCHAR(5) ), 5 ) + CONVERT(VARCHAR, MET.DTREF, 112) AS CHAVE,
                   CONVERT(VARCHAR, MET.DTREF, 112)AS CODMETA,
                   MET.CODVEND AS CODUSUR,
                   'M' AS TIPOMETA,
                   '0' AS CODIGO,
                   EMP.CODEMP AS CODFILIAL,
                   MET.DTREF AS DATAINICIAL,
                   EOMONTH(MET.DTREF) AS DATAFINAL,
                   ISNULL(MET.PREVREC, 0)AS VLVENDAPREV,
                   ISNULL(MET.QTDPREV, 0)AS QTVENDAPREV,
                   0 AS QTPESOPREV,
                   0 AS VOLUMEPREV,
                   0 AS QTDEPEDIDOSPREV,
                   0 AS CLISPOSPREV
               FROM TGMCFG CFG
                  , TGMMET MET
                  , TSIEMP EMP 
               WHERE    MET.CODMETA = CFG.CODMETA
                  AND EMP.AD_MAXIMA = 'S'
                  AND ( MET.CODEMP = 0 OR EMP.CODEMP = MET.CODEMP )
                  AND    CFG.PERIODO = 4) T
   )T2; 
GO

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

CREATE 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 >= SANKHYA.SNK_TRUNC_DATE( GETDATE() , 'DD') -7
AND STATUSMENSAGEM IS NULL;
GO

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

CREATE 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
            , SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMPED , ' ') AS VARCHAR(100) )
                         + CAST( ISNULL(  T.QT , ' ') AS VARCHAR(100) )
                         + CAST( ISNULL(  T.NUMSEQ , ' ') AS VARCHAR(100) )
                         + CAST( ISNULL(  T.PVENDA , ' ') AS VARCHAR(100) )
                         + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
                         + CAST( ISNULL(  T.PTABELA , ' ') AS VARCHAR(100) )
                        + CAST( ISNULL(  T.PERCOM , ' ') AS VARCHAR(100) )
                        + CAST( ISNULL(  T.DATA , ' ') AS VARCHAR(100) )
                   ) AS MD5LINHA
            ,T.*
         FROM ( 
      SELECT RIGHT('0000000000' + CAST( ITE.NUNOTA AS VARCHAR(10) ) , 10 ) + RIGHT('00000' + CAST(  ITE.SEQUENCIA AS VARCHAR(5) ) , 5 ) 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
         , ISNULL( 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;
GO

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

CREATE VIEW VW_MAXIMA_MIXCLIENTES AS
SELECT T2.* 
FROM (
			SELECT 
				  (SELECT MD5 FROM AD_MAXIMA_INTEGRA WHERE CHAVE = T.CHAVE AND TIPO = 13  ) AS MD5
				, SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.NUMTRANSVENDA , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODPROD  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.QT , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODCLI , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODFILIAL , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.PUNIT , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  convert(varchar, T.DTSAIDA ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.PTABELA		 , ' ') AS VARCHAR(100) )			 
							   + CAST( ISNULL(  T.CODPLPAG , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.VLRVENDA , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODAUXILIAR , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODUSUR , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA
				,T.*
			FROM ( 
					  SELECT CAST(CAB.NUNOTA AS VARCHAR(100) ) 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
						   , ISNULL(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 >= SANKHYA.SNK_TRUNC_DATE( SANKHYA.SYSDATE(), 'DD') - CONF.QTD_DIAS_HIST_VENDAS
					   
		) T
	)T2;	  	   					   
GO

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

CREATE 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
                  , SANKHYA.SNK_GET_MD5( CAST( ISNULL(     T.CODPROD   , ' ') AS VARCHAR(100) )
                                       + CAST( ISNULL(     T.CODBARRAS  , ' ') AS VARCHAR(100) )
                                    ) AS MD5LINHA
                  , T.*
          FROM ( SELECT 
                    RIGHT('0000000000' + CAST( CODPROD AS VARCHAR(10) ), 10 ) + RIGHT('0000000000000000000000000' + CAST( CODBARRA AS VARCHAR(25) ), 25 ) AS CHAVE
                  , CODPROD AS CODPROD
                  , CODBARRA AS CODBARRAS
                FROM TGFBAR
    )T
)T2; 
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 );

GO

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

CREATE 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 );
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE  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 )
;
GO

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

CREATE  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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 );
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 );
GO

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

CREATE 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 );
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE 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 );
GO

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

CREATE 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 )
;
GO

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

CREATE 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 )
;
GO

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

CREATE VIEW VW_MAXIMA_PROMOCOES_VLR AS
      SELECT T2.*
      FROM   (   SELECT (   SELECT MD5
                            FROM   AD_MAXIMA_INTEGRA
                            WHERE  CHAVE = T.CHAVE AND TIPO = 76 )
                           AS MD5
                      , 
                      SANKHYA.SNK_GET_MD5( CAST( ISNULL( T.CODPRECOPROM , ' ') AS VARCHAR(100) )							   
							   + CAST( ISNULL(  convert(varchar, T.DTINICIOVIGENCIA ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  convert(varchar, T.DTFIMVIGENCIA ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODFILIAL , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODPROD , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.PRECOFIXO , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.NUMREGIAO , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.CODCLI		 , ' ') AS VARCHAR(100) )			 
							   + CAST( ISNULL(  T.CODPRACA , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.UTILIZAPRECOFIXOREDE , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.UTILIZAPRECOFIXOFAMILIA , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  T.ORIGEMPED , ' ') AS VARCHAR(100) )
						 ) AS MD5LINHA                      
                      , T.*
                 FROM   ( 
                 		SELECT RIGHT('0000000000' + CAST( DES.NUPROMOCAO AS VARCHAR(10) ) , 10 ) + RIGHT('0000000000' + CAST(  PRO.CODPROD AS VARCHAR(10) ) , 10 ) 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 ISNULL( 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 SANKHYA.SNK_TRUNC_DATE(GETDATE(), 'DD') BETWEEN DES.DTINICIAL AND DES.DTFINAL                                                   
                         ) T) T2;
GO

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

CREATE 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 );
GO

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

CREATE 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
                , SANKHYA.SNK_GET_MD5(
								CAST( ISNULL(  NUMCAR  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  convert(varchar, T.DATAMON ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  convert(varchar, T.DTFAT ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  convert(varchar, T.DTSAIDA ,121), ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  ORIGEM_CAR  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  CODMOTORISTA  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  CODVEICULO  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  TOTPESO  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  VLTOTAL  , ' ') AS VARCHAR(100) )
							   + CAST( ISNULL(  NUMNOTAS  , ' ') AS VARCHAR(100) )
                     ) AS MD5LINHA
                , T.*
             FROM (SELECT (RIGHT('00000' + CAST(ORD.CODEMP AS VARCHAR(5)), '' ) 
										 + RIGHT('0000000000' + CAST(ORD.ORDEMCARGA AS VARCHAR(10)),'')) AS CHAVE
                        , 'OC' + (RIGHT('00000' + CAST(ORD.CODEMP AS VARCHAR(5)), '' ) 
							   + RIGHT('0000000000' + CAST(ORD.ORDEMCARGA AS VARCHAR(10)),'')) 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
GO

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

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

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

CREATE 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
    , SANKHYA.SNK_GET_MD5( ISNULL(T.CHAVE, '') + ISNULL(T.CODFILIALNF, '') + ISNULL(T.CODCLI, '') + ISNULL(T.NUMREGIAO, '')  ) AS MD5LINHA
    , T.*
  FROM (SELECT (RIGHT('00000' + CAST(PE.CODEMP AS VARCHAR(5)), 5 ) + RIGHT('0000000000' + CAST(PE.CODPARC AS VARCHAR(10)),'') + RIGHT('0000000000' + CAST(PE.CODTAB AS VARCHAR(5)),'') ) 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;

GO

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

CREATE 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);
GO               
GO

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

DECLARE
	@P_COUNT INT;
BEGIN
   SELECT @P_COUNT = COUNT(1) FROM SYSOBJECTS WHERE NAME = 'STP_PERSONALIZACAO_MAXIMA';
   
   IF(@P_COUNT = 0) BEGIN
   	RETURN;
   END;
   
   EXEC STP_PERSONALIZACAO_MAXIMA;  
END
GO

